0% found this document useful (0 votes)
36 views113 pages

3 Mech - Java Programming Unit 2

Uploaded by

mokkapunai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
36 views113 pages

3 Mech - Java Programming Unit 2

Uploaded by

mokkapunai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 113

Please read this disclaimer before

proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
JAVA PROGRAMMING

Department : Mechanical Engineering

Batch / Year :2021-2025 / II Year

Created by :
Dr J.Sathiamoorthy Associate Professor / CSE

Date : 08.08.2022

4
1. CONTENTS

Page
S. No. Contents
No
1 Contents 5

2 Course Objectives 6

3 Pre Requisites 7

4 Syllabus 8

5 Course outcomes 9

6 CO- PO/PSO Mapping 10

7 Lecture Plan 11

8 Activity based learning 12

9 Lecture Notes 15

10 Assignments 89

11 Part A Questions & Answers 91

12 Part B Questions 100

13 Supportive online Certification courses 102

14 Real time Applications 103

15 Contents beyond the Syllabus 104

16 Assessment Schedule 105

17 Prescribed Text Books & Reference Books 106

18 Mini Project Suggestions 107

5
2. COURSE OBJECTIVES

• To understand Object Oriented Programming concepts


and fundamentals of Java
• To know the principles of packages, inheritance and
interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and
generics classes
• To use the functionalities of Strings and Collections

6
3. PRE REQUISITES

• Pre-requisite Chart

20CS304 – Java Programming

20GE101 – PROBLEM SOLVING AND C PROGRAMMING

7
4. SYLLABUS

20CS304 JAVA PROGRAMMING LTPC3003


OBJECTIVES:
• To understand Object Oriented Programming concepts and fundamentals of Java
• To know the principles of packages, inheritance and interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and generics classes
• To use the functionalities of Strings and Collections
UNIT I : INTRODUCTION TO OOP AND JAVA FUNDAMENTALS 9
An Overview of Java - Data Types, Variables, and Arrays – Operators – Control
Statements – Class Fundamentals – Declaring objects – Methods – Constructors – this
keyword - Overloading methods - Overloading constructors - Access Control – Static –
Final.
UNIT II - INHERITANCE, PACKAGE AND INTERFACES 9
Inheritance: Inheritance basics, Using super, Method Overriding, Using Abstract Classes,
Using final with Inheritance – Package and Interfaces: Packages, Packages and member
access, Importing Packages, Interfaces, Static Methods in an Interface
UNIT III - MULTITHREADING, I/O AND GENERIC PROGRAMMING 9
Exception Handling: Exception-Handling Fundamentals, Exception Types, Uncaught
Exceptions, Using try and catch, Multiple catch Clauses, Nested try Statements, throw,
throws, finally, Java’s Built-in Exceptions. Multithreaded Programming: Thread Creation
UNIT IV I/O AND GENERIC PROGRAMMING 9
I/O: I/O Basics, Reading Console Input, Writing Console Output, Reading and Writing
Files – Generics: Introduction, Generic class, Bounded Types, Generic Methods, Generic
Interfaces, Generic Restrictions.
UNIT V STRING HANDLING AND COLLECTIONS 9
String Handling – Collections: The Collection Interfaces, The Collection Classes – List,
Array List, Set, Iterator – Map.
TOTAL: 45 PERIODS

OUTCOMES:
At the end of this course, the students will be able to:
CO1: Understand the Object Oriented Programming concepts and fundamentals of Java
CO2: Develop Java programs with the packages, inheritance and interfaces
CO3: Build applications using Exceptions and Threads.
CO4: Build Java applications with I/O streams and generics classes
CO5: Use Strings and Collections in applications

8
5. COURSE OUTCOME

• At the end of the course, the student should be able to:

COURSE OUTCOMES HKL


Understand the Object Oriented Programming concepts and
CO1 K2
fundamentals of Java

Develop Java programs with the packages, inheritance and


CO2 K3
interfaces

CO3 Build applications using Exceptions and Threads. K3

CO4 Build Java applications with I/O streams and generics classes K3

CO5 Use Strings and Collections in applications K3

• HKL = Highest Knowledge Level

9
6. CO - PO / PSO MAPPING

PROGRAM OUTCOMES PSO


K3, P P P
CO HKL K3 K4 K5 K5 K4, A3 A2 A3 A3 A3 A3 A2 S S S
K5 O O O
1 2 3
PO PO PO PO PO PO PO PO PO PO PO PO
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12

C203.1 K3 3 3 3 - - - - - - - - - 3 2 2

C203.2 K3 3 2 2 - - - - - - - - - 3 2 2

C203.3 K3 3 2 2 - - - - - - - - - 3 2 2

C203.4 K3 3 2 2 - - - - - - - - - 3 2 2

C203.5 K3 3 2 2 - - - - - - - - - 3 2 2

• Correlation Level - 1. Slight (Low) 2. Moderate (Medium)


3. Substantial (High) , If there is no correlation, put “-“.

10
7. LECTURE PLAN : UNIT – II

INHERITANCE, INTERFACES AND EXCEPTION HANDLING

UNIT – I LINEAR DATA STRUCTURES – LIST

Highe
Proposed Actual st
S. Mode of Delivery
Lecture Topic Lecture CO Cognit LU Outcomes Remark
No Delivery Resources
Date Date ive
Level

Inheritance: Inheritance MD1 & Define the terms


1 K2 T1
basics, MD5 Inheritance

MD1 & Understanding types


2 Inheritance Types K3 T1
MD5 of Inheritance

MD1 & Apply super keyword


3 Using super, K2 T1
MD5 in Java Programming

Define the term and


MD1 & apply Method
4 Method Overriding K3 T1
MD5 Overriding in
applications
Apply Abstract classes
Using Abstract Classes, MD1 &
5 K3 T1 in applications
MD5
CO
1 Apply final keyword in
Using final with MD1 &
6 K3 T1 applications
Inheritance MD5

Packages, Packages and Apply Packages in


MD1 &
7 member access K3 T1 Java Programming
MD5

Apply Packages in
MD1 &
8 Importing Packages K3 T1 Java Programming
MD5

Make use of interfaces


Interfaces, Static Methods
MD1 & to implement
9 in an Interface K3 T1
MD5 applications

ASSESSMENT COMPONENTS MODE OF DELEIVERY


• AC 1. Unit Test MD 1. Oral presentation
• AC 2. Assignment MD 2. Tutorial
• AC 3. Course Seminar MD 3. Seminar
• AC 4. Course Quiz MD 4 Hands On
• AC 5. Case Study MD 5. Videos
• AC 6. Record Work MD 6. Field Visit
• AC 7. Lab / Mini Project
• AC 8. Lab Model Exam
• AC 9. Project Review
8. ACTIVITY BASED LEARNING – UNIT II

COMPLETE THE PUZZLES GIVEN BELOW


1

2 3

5 6 7

10

11 12

13 14

15 16

17 18

19

Across
2. Hiding internal details and showing functionality is
6. Any entity that has state and behavior is known as
9. The ______is accessible everywhere
11. When one task is performed by different ways known as
14. _______keyword Used in a class declaration to specify the superclass; used in an interface
declaration to specify one or more super interfaces.
15. When one object acquires all the properties and behaviors of parent object known as
16. can be used to refer immediate parent class instance variable or method.
17. Binding (or wrapping) code and data together into a single unit is known as
19. The __________ is accessible only within package

Down
1. Java automatically frees the used memory for other uses
3. class which is the superclass of all classes
4. is a special type of method that is used to initialize the object.
5. keyword Included in a class declaration to specify one or more interfaces that are used by
the current class.
7. Collection of objects is called . It is a logical entity.
8. is a group of similar types of classes, interfaces, and sub- packages.
10. the________is accessible within a package and outside the
package but through inheritance only
12. keyword is used to apply restrictions on class, method, and variable.
13. The______is accessible only within class
18. Classes maintain one copy of class variables regardless of how many instances exist of that
class.
SCRAMBLED WORDS

LCIBUP _________________________

DFUEATL __________________________

ACITTS __________________________

OTCEJB __________________________

ERITPAV __________________________

TABTANCISOR __________________________

CASSL __________________________

NMSITLEEPM __________________________

GPEACKA __________________________

OABELGNLETOCACGIR __________________________

SOURCTOCTNR __________________________

DTXNEES __________________________

SRIPMHMLYOPO __________________________

ERPUS __________________________

LAFNI __________________________

JBETCO __________________________

OREPECTDT __________________________

PIEATLSUNNACO __________________________

HANETREINIC __________________________
WORD SEARCH

G A R B A G E C O L L E C T I O N
V K N D X R E P U S O K K Q L D N
P O A O S S A L C T F B D Q G H B
M T B C I G P H Z O I Q J G Y A O
R W H J O T I U W J N Y G E B T I
W Q R E E N A T B G A G F W C S P
N D B C Y C S L T L L T T G G T O
P O P N P W T T U T I B C E D N L
R C I A E G T T R S D C H E L E Y
O V S T A T I C Y U P T F D C M M
T H Y I C T A D E D C A J X V E O
E Q R R V A T V K X U T C P A L R
C O T E Q E R L I L T I O N G P P
T P T H W K D T T R W E R R E M H
E V S N F U K A S Y P T N O D I I
D O G I H H O L C B E L V D W J S
V J S P A C K A G E A Z I P S K M

abstraction class constructor


default encapsulation extends
final garbagecollection implements
inheritance object Object
package polymorphism private
protected public static
super
9. Lecture Notes
Inheritance

• Inheritance can be defined as the process of acquiring all the properties and
behaviors of one class to another
• Acquiring the properties and behavior of child class from the parent class
• Inheritance represents the IS-A relationship, also known as parent-child
relationship which is illustrated in Figure 2.1

Figure 2.1 Instance for Inheritance

Advantages of Inheritance in Java


• For Method Overriding (so runtime polymorphism can be achieved)
• For Code Reusability

Syntax:
class subClass extends superClass
{
//methods and fields
}
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also

called a derived class, extended class, or child class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits

the features. It is also called a base class or a parent class.


Types of Inheritance in Java
• Single Inheritance
• Hierarchical Inheritance
• Multilevel Inheritance
• Hybrid Inheritance
Multiple Inheritance is not supported in Java. Figure 2.2a and 2.2b illustrates the

Inheritance types in java.

Figure 2.2a Types of Inheritance


Figure 2.2b Types of Inheritance and its Syntax

Figure 2.2b Types of Inheritance and Syntax


Single Inheritance
Process of extending single subclass from single super class.

Figure 2.3 illustrates single Inheritance.

Figure 2.3 Single Inheritance

Example:
class Fruit
{
String taste = “Sweet";
void printTaste()
{
System.out.println(“Taste is: " + taste);
}
}
class Mango extends Fruit
{
String name = “Mango";
void printName()
{
System.out.println("Name is: " + name);
}
}
class SingleDemo
{
public static void main(String args[])
{
Mango m1 = new Mango();
m1.printTaste();
m1.printName();
}
}

OUTPUT
Taste is: Sweet
Name is: Mango

Hierarchical Inheritance
Process of extending more than one subclasses from single super

class. Figure 2.4 illustrates single Inheritance.

Figure 2.4 Hierarchical Inheritance


EXAMPLE

class Fruit
{
String taste = “Sweet";
void printTaste()
{
System.out.println(“Taste is: " + taste);
}
}
class Mango extends Fruit
{
String name = “Mango";
void printName()
{
System.out.println("Name is: " + name);
}
}
class Apple extends Fruit
{
String name = “Apple";
void printName()
{
System.out.println("Name is: " + name);
}
}
class HierarchicalDemo
{
public static void main(String args[])
{
Mango m1 = new Mango();
m1.printTaste();
m1.printName();
Apple a1 = new Apple();
a1.printTaste();
a1.printName();
}
}

OUTPUT
Taste is: Sweet
Name is: Mango
Taste is: Sweet
Name is: Apple

MULTILEVEL INHERITANCE
Process of extending subclass from another sub class. Figure 2.5

illustrates multilevel Inheritance.

Figure 2.5 MULTILEVEL INHERITANCE


EXAMPLE
class Fruit
{
String taste = “Sweet";
void printTaste()
{
System.out.println(“Taste is: " + taste);
}
}
class Mango extends Fruit
{
String name = “Mango";
void printName()
{
System.out.println("Name is: " + name);
}
}
class Malgova extends Mango
{
int weight = 2;
void printWeight()
{
System.out.println(“Weight is: " + weight);
}
}
class MultilevelDemo
{
public static void main(String args[])
{
Malgova m1 = new Malgova();
m1.printTaste();
m1.printName();
m1.printWeight();
}
}

OUTPUT
Taste is: Sweet
Name is: Mango
Weight is: 2

HYBRID INHERITANCE
Process of extending new classes by combining more than one forms of
inheritance. Figure 2.6 illustrates Hybrid Inheritance which combines Multilevel and
Hierarchical Inheritances.

Figure 2.6 Hybrid Inheritance


HYBRID INHERITANCE
EXAMPLE
class fruit
{
String taste = “Sweet";
void printTaste()
{
System.out.println(“Taste is: " + taste);
}
}
class mango extends fruit
{
String name = “Mango";
void printName()
{
System.out.println("Name is: " + name);
}
}
class papaya extends fruit
{
String name = “Papaya";
void printName()
{
System.out.println("Name is: " + name);
}
}
class PapayawithoutSeed extends papaya
{
int weight = 5;
void printWeight()
{
System.out.println(“Weight is: " + weight);
}
}
class HybridDemo
{
public static void main(String args[])
{
mango m1 = new mango();
m1.printTaste();
m1.printName();
PapayawithoutSeed a1 = new PapayawithoutSeed();
a1.printTaste();
a1.printName();
a1.printWeight();
}
}

OUTPUT
Taste is: Sweet
Name is: Mango
Taste is: Sweet
Name is: Papaya
Weight is: 5
Protected
members
Protected Members

• Protected access modifier is specified using the


keyword protected

• The methods or data members declared as protected


are accessible within same packge or sub classes in
different package. Figure 2.7 illustrates the working of a
access specifiers in java.

Figure 2.7 Working of Access specifiers


EXAMPLE
class A
{
int i;
protected int j;
void setij(int x,int y)
{
i=x; j=y;
}
}
class B extends A
{
int total;
void sum()
{
System.out.println("Accessing Protected member of
Super class");
total=i+j;
}
}
class PrivateAccessDemo
{
public static void main(String args[])
{
B subob = new B();
subob.setij(10,20);
subob.sum();
System.out.println("Total : "+subob.total);
}
}

OUTPUT
Accessing Protected member of Super class
Total : 30
Constructors
in sub classes
Constructors in sub classes

• Used to initialize an object when it is created.


• If no explicit constructor is specified, java will automatically supply a default
constructor.
• When an object of sub class is created, first the super class constructor will
be called and then the sub class constructor will be called.

super() in Subclass Constructor


Subclass constructor can use super() for calling super class constructor
explicitly

Syntax
subclassname()
{
super();
//
}
super() should be the first statement in subclass constructor

Uses of super

1. super() invokes the constructor of the parent class.


2. super.variable_name refers to the variable in the parent class.
3. super.method_name refers to the method of the parent class.
Uses of super

super() invokes the constructor of the parent class


Example:

class A
{
A()
{
System.out.println("Base Class default Constructor");
}}
public class B extends A
{
B()
{
super();
System.out.println("Derived Class default Constructor");
}
public static void main(String args[])
{
B b = new B();
}}

Output:
Base Class default Constructor
Derived Class default Constructor
Uses of super

super.variable_name refers to the variable in the parent class


When we have the same variable name in both super class and subclass the
superclass variable will be overridden by the sub class variable.
class A
{
int val=10;
}
public class B extends A
{
int val=20;
void disp()
{
System.out.println("Value is : "+val);
}
public static void main(String args[])
{
B b = new B();
b.disp();
}}
Output:
Value is: 20

In the above example since the variable val is present in both super class and
subclass superclass value will be overridden by the subclass. So the val 20
gets printed.
Uses of super

Case 2: If we want to access the superclass val, then we should use the
keyword super.
class A
{
int val=10;
}
public class B extends A
{
int val=20;
void disp()
{
System.out.println("Value is : "+super.val);
}
public static void main(String args[])
{
B b = new B();
b.disp();
}}
Output :
Value is: 10
Uses of super

super.method_name refers to the method of the parent class


When the parentclass method overides the child class without super
class ABC
{
void disp()
{
System.out.println("Parent Class method");
}}
public class XYZ extends ABC
{
void disp()
{
System.out.println("Child Class method");
}
void show()
{
disp();
}
public static void main(String args[])
{
XYZ obj = new XYZ();
obj.show();
}}
Output:
Child Class method
In the above example, the subclass XYZ overrides the disp() method that is
present in superclass ABC and hence SubClass disp() method is called. If we
want to call the Parent Class disp() method also means then we have to use
the super keyword for it.
Uses of super

Example: Using super keyword to access the super class method


class ABC
{
void disp()
{
System.out.println("Parent Class method");
}}
public class XYZ extends ABC
{
void disp()
{
System.out.println("Child Class method");
}
void show()
{
super.disp();
disp();
}
public static void main(String args[])
{
XYZ obj = new XYZ();
obj.show();
}}
Output:
Parent Class method
Child Class method
Quiz
1. Which of this keyword must be used to inherit a class?

a) super
b) this
c) extent
d) extends

2. Which of these is correct way of inheriting class A by class B?


a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}

3. Using which of the following, multiple inheritance in Java can be


implemented?
a) Interfaces
b) Multithreading
c) Protected methods
d) Private methods

4. Using which of the following, multiple inheritance in Java can be


implemented?
a) Interfaces
b) Multithreading
c) Protected methods
d) Private methods
5. In order to restrict a variable of a class from inheriting to subclass, how
variable should be declared?
a) Protected
b) Private
c) Public
d) Static

6. If super class and subclass have same variable name, which keyword
should be used to use super class?
a) super
b) this
c) upper
d) classname

7. What would be the result if a class extends two interfaces and both
have a method with same name and signature? Lets assume that the class
is not implementing that method.
a) Runtime error
b) Compile time error
c) Code runs successfully
d) First called method is executed successfully

8. Static members are not inherited to subclass.


a) True
b) False
Predict the output of the following code snippets
1. What will be the output of the following Java program?
class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class inheritance_demo
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
Predict the output of the following code snippets

2. What will be the output of the following Java program?


class A
{
public int i;
public int j;
A()
{
i = 1;
j = 2;
}
}
class B extends A
{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}
}
Predict the output of the following code snippets

3. What will be the output of the following Java program?


class A
{
public int i;
protected int j;
}
class B extends A
{
int j;
void display()
{
super.j = 3;
System.out.println(i + " " + j);
}
}
class Output
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
Predict the output of the following code snippets

4. What will be the output of the following Java program?


class Animal{
public Animal(){
System.out.println("Base Constructor");
}
}
class Cat extends Animal{
public Cat(){
System.out.println("Derived Constructor");

}
}
public class Program {
public static void main(String[] args) {
Cat c = new Cat();
}
}
Method
Overriding
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java. In other words, If a subclass provides the
specific implementation of the method that has been declared by one of its parent
class, it is known as method overriding
Usage of Java Method Overriding
1. Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
2. Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance)
Example Program
import java.util.Scanner;
interface maths
{
public void add();
public void sub();
public void mul();
public void div();
}
class Arithmetic implements maths
{
@Override
public void add()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values to perform addition");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a + b;
System.out.println("Sum of "+a+" and "+b+" is "+s);
}
Method Overriding
@Override
public void sub()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values to perform subtraction");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a - b;
System.out.println("Difference of "+a+" and "+b+" is "+s);
}
@Override
public void mul()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values multiplication");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a * b;
System.out.println("Product of "+a+" and "+b+" is "+s);
}
@Override
public void div()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values division");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a / b;
System.out.println("Quotient of "+a+" and "+b+" is "+s);
}
} // Arithmetic
Method Overriding
public class Main
{

public static void main(String[] args)


{
Arithmetic obj = new Arithmetic();
obj.add();
obj.sub();
obj.mul();
obj.div();
} // main()
} // Main

Output :
Enter any two integer values to perform addition
10
10
Sum of 10 and 10 is 20
Enter any two integer values to perform subtraction
20
10
Difference of 20 and 10 is 10
Enter any two integer values multiplication
10
10
Product of 10 and 10 is 100
Enter any two integer values division
1000
10
Quotient of 100 and 10 is 10

 @Override annotation is used when overriding a method in sub class


 developers overlook this feature as it is not mandatory to use this annotation while
overriding the method

Why @Override annotation is considered as a best practice in java coding?


 By using @Override annotation instruct compiler that programmer is overriding this
method
 If programmer makes any mistake such as wrong method name,
wrong parameter types while overriding, Java raises a compile time
error.
 If programmer don’t use the annotation then the sub class method
would behave as a new method, Not as the overriding method in sub
class
 It improves the readability of the code.
Abstract
classes and
methods
Abstract Classes and Methods

Data abstraction is the process of hiding the implementation details and


showing only essential information/ functionality to the user.
There are two ways to achieve abstraction in java
 Abstract classes
 Interfaces
The abstract keyword is a non-access modifier, used for classes and methods.

Abstract Classes

 A class which is declared with the abstract keyword is known as an abstract


class.
 An abstract class can have both abstract and non-abstract methods (method
with the body).
 Abstract classes cannot be instantiated (cannot be used to create objects).
But to access it, it must be inherited from another class.
 It can have constructors and static methods.
 It can have final methods.
 Although abstract classes cannot be instantiated, we can create subclasses
from it.
 We can create objects of subclasses to access members of the abstract class,
and the subclasses of abstract class must provide implementations to all the
abstract methods unless the subclass is also an abstract class.

Syntax for Abstract class


abstract class Shape
{
//attributes and methods
}
Abstract Classes and Methods

Figure.2.9 Rules for Java Abstract class


Abstract Methods

An abstract method is a method which is declared as abstract and does not


have implementation (without braces, and followed by a semicolon)
Syntax for Abstract Method:

abstract void sum(int x, double y); //no method body and abstract
Abstract method can only be used in an abstract class, and it does not have a
body.
If a class includes abstract methods, then the class itself must be
declared abstract.
Example:
public abstract class demo
{
// declare fields
// declare nonabstract methods
abstract void draw();
}
Example:
abstract class shape
{
public abstract void draw();
public void paint()
{
System.out.println(“R.M.D Engineering College");
}
public static void main(String args[])
{ shape obj= new shape(); // will generate an error
}
}
When this program gets executed, it will give compilation error, because it is
not possible to create an object of the abstract class shape.
Inheritance of Abstract Classes and Methods

An abstract class cannot be instantiated. To access the members of an


abstract class, we must inherit it.

Figure.2.10 represents the inheritance concept using abstract classes.

Figure.2.10 Inheritance using Abstract class

Program:
abstract class Shape
{
int a=3,b=4;
abstract void Area();
}
class Rectangle extends shape
{
int rectarea;
void Area()
{
rectarea=a*b;
System.out.println(“Area of rectangle is:“ +rectarea);
} }
class Triangle extends Shape
{
int triarea;
void Area()
{
triarea=(int) (0.5*a*b);
System.out.println(“Area of triangle is:“ +triarea);
}}
class Circle extends Shape
{
int circlearea;
void printarea()
{
circlearea=(int) (3.14*a*a);
System.out.println(“Area of circle is:“+circlearea);
} }
public class Demo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Area();
Triangle t=new Triangle();
t.Area();
Circle c=new Circle();
c.Area();
} }
OUTPUT:
Area of rectangle is: 12
Area of triangle is: 6
Area of circle is: 28
Abstract class with constructor, data member &
methods
An abstract class can have a data member, abstract method, non-
abstract method and constructor.
An abstract class can contain constructors in Java.A constructor of abstract class is
called when an instance of a inherited class is created.

Example :
abstract class Shape
{
Shape()
{
System.out.println(“Shape Class Created");
}
abstract void area();
void print()
{
System.out.println(“Abstraction using Constructors");
} }
//Creating a Child class which inherits Abstract class
class Rectangle extends Shape
{
void area()
{
System.out.println(“Area of Rectangle is length * breadth");
} }
//Creating a Test class which calls abstract and non-
abstract methods
class TestDemo
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
r.area();
r.print();
} }

Output:
Shape Class Created
Area of Rectangle is length * breadth
Abstraction using Constructors
Overriding of Abstract Methods
 In Java, it is mandatory to override abstract methods of the superclass in the
subclass. It is because the subclass inherits abstract methods of the
superclass.
 Since the subclass includes abstract methods, we need to override them.
Note: If the subclass is also declared abstract, it's not mandatory to override
abstract methods.
Example:
abstract class Car
{
abstract void makeSound();
public void run()
{
System.out.println(“Running smoothly.");
}}
class Honda extends Car
{
public void makeSound()
{
System.out.println(“Noise Created");
}}
class Demo1
{
public static void main(String[] args)
{
Honda s= new Honda();
s.makeSound();
s.run();
}}
Output:
Noise Created
Running smoothly
We have created an abstract class Car. The class contains an abstract method
makeSound() and a non-abstract method run(). The subclass Car overrides
the abstract method makeSound().
Quiz
1. Which of these class is superclass of every class in Java

a) String class
b) Object class
c) Abstract class
d) ArrayList class

2. What will be the output of the following Java code?

class Output

public static void main(String args[])

Object obj = new Object();

System.out.print(obj.getclass());

a) Object
b) class Object
c) class java.lang.Object
d) Compilation Error

3. Which of these keywords are used to define an abstract class?


a) abst
b) abstract
c) Abstract
d) abstract class
4. If a class inheriting an abstract class does not define all of its function
then it will be known as?
a) abstract
b) A simple class
c) Static class
d) None of the mentioned

5. Which of these is not a correct statement?


a) Every class containing abstract method must be declared abstract
b) Abstract class defines only the structure of the class not its implementation
c) Abstract class can be initiated by new operator
d) Abstract class can be inherited

6. Which of these keywords can be used to prevent inheritance of a class?


a) super
b) constant
c) class
d) final
Predict the output of the following code snippets

1. What will be the output of the following Java program?


abstract class A
{
int i;
abstract void display();
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class Abstract_demo
{
public static void main(String args[])
{
B obj = new B();
obj.j=2;
obj.display();
}
}
Predict the output of the following code snippets

2. What will be the output of the following Java program?


class A
{
int i;
int j;
A()
{
i = 1;
j = 2;
}
}
class Output
{
public static void main(String args[])
{
A obj1 = new A();
System.out.print(obj1.toString());
}
}

Online Assessment Test


https://hr.gs/oopstest2
Final methods
and classes
Final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class

Java final variable


A final variable is a variable whose value cannot be changed at anytime once
assigned, it remains as a constant forever.
Example:
public class Travel
{
final int SPEED=60;
void increaseSpeed()
{
SPEED=70;
}
public static void main(String args[])
{
Travel t=new Travel();
t.increaseSpeed();
}
}
Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Travel.SPEED cannot be assigned.
The above code will give you Compile time error, as we are trying to change the
value of a final variable ‘SPEED’.
Java final method
When you declare a method as final, then it is called as final method. A final
method cannot be overridden.
Example
package com.javainterviewpoint;
class Parent
{
public final void disp()
{
System.out.println("disp() method of parent class");
}
}
public class Child extends Parent
{
public void disp()
{
System.out.println("disp() method of child class");
}
public static void main(String args[])
{
Child c = new Child(); c.disp();
}
}
Output : We will get the below error as we are overriding the disp() method of the
Parent class.
Exception in thread "main" java.lang.VerifyError: class com.javainterviewpoint.Child
overrides final method disp.()
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
Packages in
Java
Packages

• Java package is a group of similar types of classes, interfaces and sub-packages.

• Package in java can be categorized in two form, built-in package and user-defined
package

• There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.

Advantage of Java Package

• Java package is used to categorize the classes and interfaces so that they
can be easily maintained.

• Java package provides access protection

• Java package removes naming collision


Examples of some existing packages in Java are

• java.lang − bundles the fundamental classes

• java.io − classes for input , output functions are bundled in this


package

Programmers can define their own packages to bundle group of classes/interfaces,


etc. It is a good practice to group related classes implemented, so that a
programmer can easily determine that the classes, interfaces, enumerations, and
annotations are related.

Since the package creates a new namespace there is no chance for any name
conflicts with names in other packages. Using packages, it is easier to provide
access control and it is also easier to locate the related classes.
Creating a Package

While creating a package, name for the package is chosen and included in
the package statement at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that are included in the package.
The package statement should be the first line in the source file.
There can be only one package statement in each source file, and it applies to all
types in the file. If a package statement is not used then the class, interfaces,
enumerations, and annotation types will be placed in the current default package.

To compile the Java programs with package statements, you have to use -d option
as shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination,
and the compiled class files will be placed in that folder

Now a package/folder with the name mypack will be created in the current directory
and these class files will be placed in it for the Example Code 1.

Example Code 1:

• The package keyword is used to create a package in java.


package mypack;
public class Simple {
public void intro() {
System.out.println("Welcome to package");
}
}

Compiling Java package

Syntax

javac -d directory java filename

Example to Compile:

javac -d . Simple.java

How to run java package program

Example to Execute:

java mypack.Simple
Example Code 2:
// Create a Java Source File named A.java
package pack;
public class A {
public int Add(int a, int b) {
return (a + b);
}
}

// Create a Java Source File named B.java


package pack;
public class B {
public int Sub(int a, int b) {
return (a - b);
}
}

// Create a Java Source File named C.java


package pack;
public class C {
public int Mul(int a, int b) {
return (a * b);
}
}

// Create a Java Source File named Arithmetic.java


import java.util.*;
import java.io.*;
import pack.A;
import pack.B;
import pack.C;
public class Arithmetic {
public static void main(String args[]) {
int d, ch;
String ns;
Scanner in = new Scanner(System.in);
System.out.println("\n Enter the first value:");
int a1 = in.nextInt();
System.out.println("\n Enter the second value:");
int b1 = in.nextInt();

do {
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
System.out.println("4.Exit");
System.out.println("Enter the choice");
ch = in.nextInt();
switch (ch) {
case 1:
A a = new A();
d = a.Add(a1, b1);
System.out.println("Addition values:" + d);
break;
case 2:
B b = new B();
d = b.Sub(a1, b1);
System.out.println("Subtraction values:" + d);
break;
case 3:
C c = new C();
d = c.Mul(a1, b1);
System.out.println("Multiplication values:" + d);
break;
}
} while (ch < 4);
}
}
Output:
Enter the first value: 5
Enter the Second Value: 6
1.Addition
2.Subtraction
3.Multiplication
4.Exit
Enter the choice
1
Addition values:11
1.Addition
2.Subtraction
3.Multiplication
4.Exit
Enter the choice
2
Subtraction values:-1
1.Addition
2.Subtraction
3.Multiplication
4.Exit
Interfaces:
Defining an interface, implementing interface,
differences between classes and interfaces and
extending interfaces
Interface in Java

An interface in java is a blueprint of a class. It has static constants and


abstract methods.The interface in java is a mechanism to achieve abstraction and
multiple inheritance.
Interface is declared by using interface keyword. It provides total
abstraction; means all the methods in interface are declared with empty body and
are public and all fields are public, static and final by default. A class that implement
interface must implement all the methods declared in the interface.

Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Internal addition by compiler
The java compiler adds public and abstract keywords before the interface method.
More, it adds public, static and final keywords before data members. In other words,
Interface fields are public, static and final by default, and methods are public and
abstract.

Figure.2.11 Interface compilation


Relation between Class and Interface
As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.

Figure.2.12 extending class and interface

interface Bank {
float rateOfInterest();
}

class SBI implements Bank {


@Override
public float rateOfInterest() {
return 9.15f;
}
}
class ICICI implements Bank {
@Override
public float rateOfInterest() {
return 9.7f;
} Output
} ROI: 9.15
public class JavaApplication4 {
public static void main(String[] args) {
Bank b = new SBI();
System.out.println("ROI: " + b.rateOfInterest());

}
}
Example:
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6(); obj.print();
}
}

Output:

Hello
Example:
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();
d.draw();
}
}
Output:
drawing circle

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces
i.e. known as multiple inheritance.

Figure.2.13 Multiple Inheritance


Example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}

class A7 implements Printable,Showable


{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
Interface inheritance
A class implements interface but one interface extends another interface .
Example:
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}

class TestInterface4 implements Showable


{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Output:
Hello Welcome
Nested Interface in Java
An interface can have another interface i.e. known as nested interface.

Example
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
}

Key points to remember about interfaces:


1.We can’t instantiate an interface in java. That means we cannot create the object
of an interface
2.Interface provides full abstraction as none of its methods have body. On the other
hand abstract class provides partial abstraction as it can have abstract and
concrete(methods with body) methods both.
3.“implements” keyword is used by classes to implement an interface.
4.While providing implementation in class of any method of an interface, it needs to
be mentioned as public.
5.Class that implements any interface must implement all the methods of that
interface, else the class should be declared abstract.
6.Interface cannot be declared as private, protected or transient.
7.All the interface methods are by default abstract and public.
8.Variables declared in interface are public, static and final by default.
interface Try
{
int a=10; public int a=10;
public static final int a=10; final int a=10;
static int a=0;
}
All of the above statements are identical.
9. Interface variables must be initialized at the time of declaration otherwise
compiler will throw an error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is not
initialized at the time of declaration.
10. Inside any implementation class, you cannot change the variables declared in
interface because by default, they are public, static and final. Here we are
implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got
compilation error as the variable x is public static final by default and final variables
can not be re-initialized. class Sample implements Try
{
public static void main(String args[])
{
x=20; //compile time error
}
}
11. An interface can extend any interface but cannot implement it. Class implements
interface and interface extends interface.
12. A class can implement any number of interfaces.
13. If there are two or more same methods in two interfaces and a class implements
both interfaces, implementation of the method once is enough.
interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
14. A class cannot implement two interfaces that have methods with same name but
different return type.
interface A
{
public void aaa()
}
interface B
{
public int aaa();
}
class Central implements A,B
{
public void aaa() // error
{
}
public int aaa() // error
{
}
public static void main(String args[])
{
}
}
15. Variable names conflicts can be resolved by interface name.

interface A

int x=10;

interface B

int x=100;

}
class Hello implements A,B
{
public static void Main(String args[])
{
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}

Advantages of interface in java:


▪ Without bothering about the implementation part, we can achieve the security
of Implementation.
▪ In java, multiple inheritance is not allowed, however you can use interface to
make use of it as you can implement more than one interface.

Difference between Abstract Class and Interface

ABSTRACT CLASS INTERFACE

1)Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Sinc Java 8, it can have default and static
methods also.
2)Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3)Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4)Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5)The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
7) An abstract class can be extended using An interface class can be implemented using
keyword extends. keyword implements
Quiz
1. Which of these can be used to fully abstract a class from its
implementation?

a) Objects

b) Packages

c) Interfaces

d) None of the Mentioned

2. All methods must be implemented of an interface.

a) True

b) False

3. What type of variable can be defined in an interface?

a) public static

b) private final

c) public final

d) static final

4. What does an interface contain?

a) Method definition

b) Method declaration

c) Method declaration and definition

d) Method name
5. What type of methods an interface contain by default?

a) Abstract
b) Static
c) Final
d) private

6. What will happen if we provide concrete implementation of method in


interface?

a) The concrete class implementing that method need not provide implementation
of that method
b) Runtime exception is thrown
c) Compilation failure
d) Method not found exception is thrown
7. What happens when a constructor is defined for an interface?

a) Compilation failure
b) Runtime Exception
c) The interface compiles successfully
d) The implementing class will throw exception

8. What happens when we access the same variable defined in two


interfaces implemented by the same class?

a) Compilation failure
b) Runtime Exception
c) The JVM is not able to identify the correct variable
d) The interfaceName.variableName needs to be defined
Predict the output of the following code snippets

1. What will be the output of the following Java program?


interface calculate
{
void cal(int item);
}
class display implements calculate
{
int x;
public void cal(int item)
{
x = item * item;
}
}
class interfaces
{
public static void main(String args[])
{
display arr = new display;
arr.x = 0;
arr.cal(2);
System.out.print(arr.x);
}
}
Java final class
A final class cannot be extended(cannot be subclassed), lets take a look into the
below example package com.javainterviewpoint;

Example

final class Parent


{
}
public class Child extends Parent
{
public static void main(String args[])
{
Child c = new Child();
}
}

Output :
We will get the compile time error like “The type Child cannot subclass the final
class Parent”.
Exception in thread "main" java.lang.Error: Unresolved compilation problem
Static Methods in a Interface
Static Methods in Interface are those methods, which are defined in
the interface with the keyword static. Unlike other methods in Interface, these static
methods contain the complete definition of the function and since the definition is
complete and the method is static, therefore these methods cannot be overridden or
changed in the implementation class.
a simple static method is defined and declared in an interface which is
being called in the main() method of the Implementation Class InterfaceDemo.
Unlike the default method, the static method defines in Interface hello(), cannot be
overridden in implementing the class.
interface NewInterface
{
static void hello() // static method
{
System.out.println("Hello, New Static Method Here");
}

// Public and abstract method of Interface


void overrideMethod(String str);
}

// Implementation Class
public class InterfaceDemo implements NewInterface {

public static void main(String[] args)


{
InterfaceDemo interfaceDemo = new InterfaceDemo();

// Calling the static method of interface


NewInterface.hello();

// Calling the abstract method of interface


interfaceDemo.overrideMethod("Hello, Override Method here");
}

// Implementing interface method


Output:
@Override Hello, New Static Method Here
public void overrideMethod(String str) Hello, Override Method here
{
System.out.println(str);
}
}
10. Assignment
1. Develop a java application with Employee class with Emp_name, Emp_id,
Address, Mail_id, Mobile_no as members. Inherit the classes Assistant Professor,
Associate Professor and Professor from employee class. Add Basic Pay (BP) as the
member of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12%
of BP as PF, 0.1% of BP for staff club fund. Generate pay slips for the employees
with their gross and net salary.

2. Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains only the method print Area () that prints the
area of the given shape.

3. Develop a Java application to generate Electricity bill. Create a class with the
following members: Consumer no., consumer name, previous month reading,
current month reading, type of EB connection (i.e domestic or commercial).
Compute the bill amount using the following tariff.

If the type of the EB connection is domestic, calculate the amount to be paid as


follows:

• First 100 units - Rs. 1 per unit 101-200 units - Rs. 2.50 per unit
• 201 -500 units - Rs. 4 per unit > 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as
follows:

• First 100 units - Rs. 2 per unit 101-200 units - Rs. 4.50 per unit
• 201 -500 units - Rs. 6 per unit > 501 units - Rs. 7 per unit

4. Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains only the method print Area () that prints the
area of the given shape.
11. Part A
Question and Answers
PART - A

1. What is meant by inheritance? (K1)(CO2)


• Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another class.

2. What is super class? (K1)(CO2)


• The class that is being inherited is called Super or Base class.

• Form this above figure, Class A is being inherited by Class B. So, Class A is a
Super class or Base class.

3. What is sub class? (K1)(CO2)


• The class that inherits the properties of another class is called sub class or
derived class.

• Form this above figure, Class B is inherits the properties of Class A. So, Class
B is a Sub class or Derived class.

4. What is the difference between superclass and subclass? (K1)(CO2)


• The superclass is the class from which another class gets inherited.
• The subclass is the class which inherits the features of a superclass.
• The subclass can extend the features of the super class and add its own
features.
PART - A

5. What are the types in inheritance? (K1)(CO2)


• The types of inheritance are:
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
• Hybrid Inheritance

6. What is single inheritance? (K1)(CO2)


• In single inheritance, one class inherits the properties of another.

• Here, Class A is a parent class and Class B is a child class which inherits the
properties and behavior of the parent class.

7. What is multilevel inheritance? (K1)(CO2)


• When a class is derived from a class which is also derived from another class,
i.e. a class having more than one parent class but at different levels, such
type of inheritance is called Multilevel Inheritance.
PART - A

• A is the parent class for B and class B is the parent class for C.
• Here, class B inherits the properties and behavior of class A and class C
inherits the properties of class B.
• So in this case class C implicitly inherits the properties and methods of class
A along with Class B.

8. What is hierarchical inheritance? (K1)(CO2)


• When a class has more than one child classes (sub classes) or in other words,
more than one child classes have the same parent class, then such kind of
inheritance is known as hierarchical.

• Here, Class B and C are the child classes which are inheriting from the parent
class i.e Class A.

9. What are the advantages of inheritance? (K1)(CO2)


• Code reusability
• Establish a relationship between different classes.
• It promotes polymorphism by allowing method overriding

10. Illustrate the usage of super keyword? (K2)(CO2)


• super keyword is used to access the members of parent class.
• In Java, super keyword is used to refer to immediate parent class of a child
class.
• The usage of super keyword:
• To access the variables of parent class
• To access the methods of parent class
• To call constructor of the parent class
PART - A

11. Tell, Can you use both this() and super() in a Constructor? (K1)(CO2)
• NO, because both super() and this() must be first statement inside a
constructor. Hence we cannot use them together.

12. What is meant by abstract class? (K1)(CO2)


• A class which is declared using abstract keyword known as abstract
class.
• An abstract class may or may not have abstract methods.
• We cannot create object of abstract class.
• It is used for abstraction.
• Syntax:
abstract class class_name
{
// statements
}

13. What are the rules for creating abstract method? (K1)(CO2)
• Method that is declared without any body within an abstract class is
called abstract method.
• Syntax:
abstract return_type function_name();
• The definition of abstract method is should be in the child class.

14. Describe the purpose of the keyword “final”. (K1)(CO2)


• Final keyword is used to apply restrictions on class, method and variable.
• final class can't be inherited
• final method can't be overridden
• final variable value can't be changed.

15. Define Interface. (K2)(CO2)


• An interface is a collection of abstract methods and constant variables.
• This is the only way by which we can achieve full abstraction.
PART - A

16. Differentiate interface and class. (K4)(CO2)

S.No Class Interface

1 The variables of the class can The variables of an interface are


be constant or variable always declared as constant. i.e
their values are final.
2 The class definition can contain The methods in an interface must
method definition. The methods be abstract. These methods are
can be abstract or non-abstract defined by the class that implements
the interface
3 Objects can be created Objects cannot be created. It can
only be inherited
4 It can use access specifiers like It can only use the public access
public, private or protected specifier.

17. Differentiate interface and abstract class. (K4)(CO2)

S.No Interface Abstract Class


1 Interface contains abstract Abstract class can have methods
methods and cannot have with implementation and abstract
implementations methods without implementations
2 Variables of a interface are Variables of an abstract class may
final contain non-final variables
3 Members of an interface are Members of a abstract class can be
public by default public, private, protected etc.,
4 A class can implement multiple A class can extend only one abstract
interfaces class
5 Interfaces are slow compared Faster than interface
to abstract class due to extra
indirection.
PART - A

18. Define multiple Inheritance. (K1)(CO2)


• One class inherits multiple classes, it is known as multiple inheritance.
• It is not supported in Java. It is implemented by using interface

19. Define Hybrid Inheritance. (K1)(CO2)


• Process of combining two or more types of inheritance is called Hybrid
inheritance.

Class Roll

Class Mark Interface Sports

Class Student

• From this example, Hybrid inheritance is a combination of Multi level


inheritance and multilevel inheritance.

20. What are the advantages of Interface? (K1)(CO2)


• It Support multiple inheritance
• It helps to achieve abstraction
• It can be used to achieve loose coupling.

21. What is abstraction? (K1)(CO2)


• Abstraction is the process of hiding the implementation details & showing
only the functionality.
PART - A

22. How will you define interface in java program. (K3)(CO2)


• An interface is declared by using the interface keyword. It provides total
abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default. A class
that implements an interface must implement all the methods declared in
the interface.

23. What are the four types of access modifiers? (K1)(CO2)


• There are 4 types of java access modifiers:
• private
• default
• protected
• Public

24. What is the difference between a static and a non-static inner class?
(K1)(CO2)
• A non-static inner class may have object instances that are associated with
instances of the class's outer class. A static inner class does not have any
object instances.

25. What modifiers may be used with top-level class? (K1)(CO2)


• Public, abstract and final can be used for top-level class.

26. List out the Java packages. (K1,CO1)


• The Java packages are,
1.java.lang
2.java.io
3.java.awt
4.java.net
5.java.applet
6.java.rmi
Part - A
27. Define abstract class. (K1, CO1)
A class declared with abstract keyword and have zero or more abstract
methods are known as abstract class. The abstract classes are incomplete classes.
Therefore to use, strictly need to extend the abstract classes to a concrete class.
28. Define final class. (K1, CO1)
A class declared with the final keyword is a final class and it cannot be
extended by another class, for example java.lang.System class.
29. Define static class. (K1, CO1)
Static classes are nested classes means a class declared within another
class as a static member is called a static class.
12. Part B
Questions
PART - B

1. Define Inheritance? With diagrammatic illustration and java programs illustrate


the different types of inheritance.(13) (K1)(CO2)

2. Write briefly on Abstract classes with an example.(13) (K3)(CO2)

3. How to define an interface? Why do the members of interface are static and
final? (13) (K3)(CO2)

4. Write a java program of hybrid inheritance with own example.(13) (K3)(CO2)

5. Explain the types of package with its importance (K1, CO1)

6. Define Package? How does compiler locate packages? Explain arrays in java?
(K1, CO1)
13. Online Certifications
1. https://www.hackerrank.com/skills-verification/java_basic
2. https://www.sololearn.com/Course/Java/
3. https://www.coursera.org/specializations/object-oriented-programming
4. https://www.udemy.com/course/java-the-complete-java-developer-course/ [Paid]
5. https://nptel.ac.in/courses/106/105/106105191/ [Paid]
6. https://education.oracle.com/java-se-8-fundamentals/courP_3348 [Paid]
14. Real Time Applications

• Scientific Applications

• Financial Applications

• Games

• Desktop Applications

• Web Applications

103
15. Content Beyond Syllabus
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

interface Printable
{
void print();
}
interface Showable
{
void show();
}
class MultipleDemo implements Printable,Showable
{
public void print(){System.out.println("Hello");
}
public void show(){System.out.println("Welcome");
}

public static void main(String args[])


{
MultipleDemo obj = new MultipleDemo ();
obj.print();
obj.show();
}
}
16. Assessment Schedule
• Tentative schedule for the Assessment During
2021-2022 odd semester

Name of the
S.NO Start Date End Date Portion
Assessment

1 IAT 1 20.09.2021 25.09.2021 UNIT 1 & 2

2 IAT 2 22.10.2021 28.10.2021 UNIT 3 & 4

3 REVISION 13.11.2021 16.11.2021 UNIT 5 , 1 & 2

4 MODEL 18.11.2021 29.11.2021 ALL 5 UNITS

105
17. Prescribed Text Books and References

TEXTBOOK:

1. Herbert Schildt, Java:The complete reference, 11th Edition,


McGraw Hill Education, 2019.

REFERENCES:

1. Cay S. Horstmann, Gary cornell, “Core Java Volume –I


Fundamentals”, 11th Edition, Prentice Hall, 2019.
2. Paul Deitel, Harvey Deitel, Java SE 8 for programmers, 3rd
Edition, Pearson, 2015.
3. Steven Holzner, Java 2 Black book, Dreamtech press, 2011.
4. Timothy Budd, Understanding Object-oriented programming with
Java, Third Edition, Pearson Education, 2008.
18. Mini Project
Interest Calculator
Calculate interest based on the type of the account and the status
of the account holder. The rates of interest changes according to
the amount (greater than or less than 1 crore), age of account
holder (General or Senior citizen) and number of days if the type
of account is FD or RD.
Some sample rates are given in the below tables: Rate of FD
citizen) and interest for amounts below 1 Crore:

Current Rates of interest


Maturity Period General Senior Citizen
7 days to 14 days 4.50 5.00

15 days to 29 days 4.75 5.25

30 days to 45 days 5.50 6.00

45 days to 60 days 7 7.50

61 days to 184 days 7.50 8.00

185 days to 1 year 8.00 8.50

Rate of FD interest for amounts above 1 Crore:

Maturity Period Interest Rate


7 days to 14 days 6.50
15 days to 29 days 6.75
30 days to 45 days 6.75
45 days to 60 days 8

61 days to 184 days 8.50

185 days to 1 year 10.00


Rate of RD interests:
Current Rates of interest
Maturity
General Senior Citizen
Period
6 months 7.50 8.00
9 months 7.75 8.25
12 months 8.00 8.50
15 months 8.25 8.75
18 months 8.50 9.00
21 months 8.75 9.25

SB Account interest rates:


Type of Account Interest Rate

Normal 4%
NRI 6%

Requirements:
1. Separate classes should be created for the different types of
accounts.
2. All classes should be derives from an abstract class named
‘Account’ which contains a method called ‘calculateInterest’.
3. Implement the calculateInterest method according to the type of
the account, interest rates, amount and age of the account holder.
4. If the user is entering any invalid value (For eg. Negative value) in
any fields, raise a user defined exception.
Sample class structure is given below:

Account(Abstract)

double interestRate

double amount
FDAccount
double interestRate
double amount
int noOfDays
ageOfACHolder
abstract double calculateInterest()

SBAccount
double interestRate
double amount
abstract double calculateInterest()

RDAccount
double interestRate
double amount
int noOfMonths;
double
monthlyAmount;
abstract double calculateInterest()

Hint: Use method overriding


Sample Output:
Select the option:

1.Interest Calculator –SB


2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit
1

Enter the Average amount in your account: 10000


Interest gained: Rs. 400 Select the option:
1.Interest Calculator –SB
2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit
2

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 65


Interest gained is: 800 Select the option:

1.Interest Calculator –SB


2.Interest Calculator –FD
3.Interest Calculator –RD
4.Exit

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 34

Interest gained is: 750


Select the option:

1. Interest Calculator –SB


2. Interest Calculator –FD
3. Interest Calculator –RD
4. Exit

Enter the FD amount: 10000

Enter the number of days: -7

Enter your age: 78

Invalid Number of days. Please enter correct values.


Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.

You might also like