0% found this document useful (0 votes)
64 views94 pages

Unit 2 P1

The document discusses object-oriented programming concepts in Java like inheritance, polymorphism, method overloading and overriding, aggregation, and provides examples to explain these concepts. Inheritance allows classes to inherit properties from parent classes, while method overloading has methods with the same name but different parameters, and method overriding involves redefining inherited methods in subclasses.

Uploaded by

anurag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views94 pages

Unit 2 P1

The document discusses object-oriented programming concepts in Java like inheritance, polymorphism, method overloading and overriding, aggregation, and provides examples to explain these concepts. Inheritance allows classes to inherit properties from parent classes, while method overloading has methods with the same name but different parameters, and method overriding involves redefining inherited methods in subclasses.

Uploaded by

anurag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

UNIT-2

Presented By:
Deepak Kumar Sharma
Asst. Professor
SoCS UPES Dehradun
UNIT-II

• Extended Class, Constructors in Extended classes, Inheriting and Redefining


Members
• Type Compatibility and Conversion, protected, final Methods and Classes
• Abstract methods and classes, Object Class

• Designing extended classes, Single Inheritance versus Multiple Inheritance

• Interface, Interface Declarations, Extending Interfaces, Working with Interfaces

• Marker Interfaces, When to Use Interfaces, Package naming, type imports


• Package access, package contents, package objects and specifications

Deepak Sharma, Asst. Professor UPES Dehradun


Inheritance

• Inheritance is a mechanism in which one class acquires the property of another


class.
• E.g. a child inherits the traits of his/her parents.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.

WHY INHERITANCE?

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


• For Code Reusability.

Deepak Sharma, Asst. Professor UPES Dehradun


Key Terms:
 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.
 Reusability: As the name specifies, reusability is a mechanism
which facilitates you to reuse the fields and methods of the existing
class when you create a new class.You can use the same fields and
methods already defined in the previous class.

Deepak Sharma, Asst. Professor UPES Dehradun


Extends
• The extends keyword indicates that you are making a new class that derives
from an existing class.

class Subclass-name extends Superclass-name


{
//methods and fields
}

Deepak Sharma, Asst. Professor UPES Dehradun


Example:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
O/P:
Programmer salary is:40000.0
Bonus of programmer is:10000
Deepak Sharma, Asst. Professor UPES Dehradun
Example:
class Vehicle {
protected String brand = "TATA";
public void honk() {
System.out.println("Horn PLz!");
}
} O/P:
class Car extends Vehicle { Horn PLz!
TATA NEXON
private String modelName = "NEXON";
public static void main(String[] args) {
Car myFastCar = new Car();
myFastCar.honk();
System.out.println(myFastCar.brand + " " + myFastCar.modelName);
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
Types of inheritance in java
 On the basis of class, there can be three types of inheritance in java:
 Single
 multilevel
 hierarchical

Deepak Sharma, Asst. Professor UPES Dehradun


Types of Inheritance
 In java programming, multiple and hybrid inheritance is supported
through interface only.

Note: Multiple inheritance is not supported in Java through class.


Deepak Sharma, Asst. Professor UPES Dehradun
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}

class Dog extends Animal{


void bark(){System.out.println("barking...");}
}

class TestInheritance{ O/P:


public static void main(String args[]){ barking...
Dog d=new Dog(); eating...
d.bark();
d.eat();
}}

Deepak Sharma, Asst. Professor UPES Dehradun


Multilevel Inheritance Example
 When there is a chain of inheritance, it is known as multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}

class Dog extends Animal{


void bark(){System.out.println("barking...");}
}

class BabyDog extends Dog{


void weep(){System.out.println("weeping...");}
} O/P:
weeping...
class TestInheritance2{ barking...
public static void main(String args[]){ eating...
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}} Deepak Sharma, Asst. Professor UPES Dehradun
Hierarchical Inheritance Example
 When two or more classes inherits a single class.
class Animal{
void eat(){System.out.println("eating...");}
}

class Dog extends Animal{


void bark(){System.out.println("barking...");}
}

class Cat extends Animal{


void meow(){System.out.println("meowing...");}
}

class TestInheritance3{ Output:


public static void main(String args[]){
Cat c=new Cat();
meowing...
c.meow(); eating…
c.eat();
//c.bark();//C.T.Error
}} Deepak Sharma, Asst. Professor UPES Dehradun
Why multiple inheritance is not supported in java?
 To reduce the complexity and simplify the language, multiple inheritance is
not supported in java.
 To avoid ambiguity while calling same method present in both parent classes.

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

Output: Compile time Error


Deepak Sharma, Asst. Professor UPES Dehradun
Aggregation in Java

 If a class have an entity reference, it is known as Aggregation.


Aggregation represents HAS-A relationship (part of relationship).

class Employee{
int id;
String name;
Address address;//Address is a class
...
}

 Employee has an entity reference address, so relationship is


Employee HAS-A address.
Deepak Sharma, Asst. Professor UPES Dehradun
Example of Aggregation
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call)
return pi*rsquare;
}

public static void main(String args[]){


Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
Example of Aggregation
class Address {
String city; class Person {
String state; String name;
Address address = new Address(“Dehradun", “UK");
Address(String city, String state) {
this.city = city; Person(String name) {
this.state = state; this.name = name;
} }

// You can use this method if you void display() {


//want a formatted address. System.out.println(name + " lives in " +
String getFormattedAddress() { address.getFormattedAddress());
return city + ", " + state; }
} }
}
public class Main {
public static void main(String[] args) {
Person person = new Person(“Anuj");
person.display();
}
}

Output: Anuj lives in Dehradun, UK


When use Aggregation?

 Code reuse is also best achieved by aggregation when there is no is-a


relationship.
 Inheritance should be used only if the relationship is-a is maintained
throughout the lifetime of the objects involved; otherwise,
aggregation is the best choice.

Deepak Sharma, Asst. Professor UPES Dehradun


Method Overloading and Overriding

Deepak Sharma, Asst. Professor UPES Dehradun


Method Overloading
 If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
 Method overloading increases the readability of the program.
 There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
 In Java, Method Overloading is not possible by changing the return
type of the method only.

Deepak Sharma, Asst. Professor UPES Dehradun


class OverloadDemo { //method overloading
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
class Overload {
} public static void main(String args[]) {
} OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
} }
Can we overload java main() method?
 Yes, by method overloading.You can have any number of main
methods in a class by method overloading.
 But JVM calls main() method which receives string array as
arguments only.
class TestOverloading{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}

Output: main with String[]

Deepak Sharma, Asst. Professor UPES Dehradun


Method Overriding in Java
 If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
 Method overriding is used to provide the specific implementation of
a method which is already provided by its superclass.
 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).

Deepak Sharma, Asst. Professor UPES Dehradun


Problem without method overriding
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}

//Creating a child class


class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
} Output: Vehicle is running

Problem: Need to provide a specific implementation of run() method in subclass


Deepak Sharma, Asst. Professor UPES Dehradun
Example: method overriding
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");
}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output: Bike is running safely

Deepak Sharma, Asst. Professor UPES Dehradun


class Bank{
Example: Method Overriding
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;} Output:
} SBI Rate of Interest: 8
//Test class to create objects and call the methods ICICI Rate of Interest: 7
class Test2{ AXIS Rate of Interest: 9
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
Can we override static method?
• No, a static method cannot be overridden.
• the static method is bound with class whereas
instance method is bound with an object.

Can we override java main method?

• No, because the main is a static method.

Deepak Sharma, Asst. Professor UPES Dehradun


Super Keyword

 The super keyword in Java is a reference variable which is used to


refer immediate parent class object.
 Whenever you create the instance of subclass, an instance of parent
class is created implicitly which is referred by super reference
variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

Deepak Sharma, Asst. Professor UPES Dehradun


Super- to refer immediate parent class instance variable
 to access the data member or field of parent class.
 if parent class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper{
public static void main(String args[]){ Output:
Dog d=new Dog(); Black
d.printColor(); white
}}
Deepak Sharma, Asst. Professor UPES Dehradun
eating... barking...

Super- to invoke parent class method


 It should be used if subclass contains the same method as parent
class (Methods are overridden).
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper{ Output:
public static void main(String args[]){ eating…
Dog d=new Dog(); barking…
d.work();
}} Deepak Sharma, Asst. Professor UPES Dehradun
eating... barking...

Super() - to invoke parent class constructor


 To invoke parent class constructor.

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper{
public static void main(String args[]){ Output:
Dog d=new Dog(); animal is created
}} dog is created

Deepak Sharma, Asst. Professor UPES Dehradun


eating... barking...

Super() - to invoke parent class constructor


 Note: super() is added in each class constructor automatically as the
first statement by compiler if there is no super() or this().

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog(); Output:
}} animal is created
dog is created

Deepak Sharma, Asst. Professor UPES Dehradun


Example- Super()
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){ Output:
Emp e1=new Emp(4,"aman",95000f); 4 aman 95000
e1.display();
}} Deepak Sharma, Asst. Professor UPES Dehradun
Instance initializer block- Example
 Instance Initializer block is used to initialize the instance data
member.
 It run each time when object of the class is created.

class Bike{
int speed;

Bike(){System.out.println("speed is "+speed);}

{speed=100;}
Output:
speed is 100
public static void main(String args[]){
speed is 100
Bike b1=new Bike();
Bike b2=new Bike();
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
Instance initializer block
 It run each time when object of the class is created.

We can directly Why initializer block?


assign a value
in instance data • To perform some operations while
member assigning value to instance data member
• e.g. a for loop to fill a complex array
class Bike{ or error handling etc.
int speed=100;
}

There are three places in java where you can perform operations:
• method
• constructor
• block

Deepak Sharma, Asst. Professor UPES Dehradun


Instance initializer block
What is invoked first, instance initializer block or constructor?
class Bike8{
int speed;

Bike8(){System.out.println("constructor is invoked");}

{System.out.println("instance initializer block invoked");}


Output:
public static void main(String args[]){ instance initializer block invoked
Bike8 b1=new Bike8(); constructor is invoked
Bike8 b2=new Bike8(); instance initializer block invoked
} constructor is invoked
}

• It seems that instance initializer block is firstly invoked but NO.


• Instance intializer block is invoked at the time of object creation.
Note: The java compiler copies the code of instance initializer block in every
constructor.
Deepak Sharma, Asst. Professor UPES Dehradun
Rules for instance initializer block :
Three rules:
 The instance initializer block is
created when instance of the class
is created.
 The instance initializer block is
invoked after the parent class
constructor is invoked (i.e. after
super() constructor call).
 The instance initializer block
comes in the order in which they
appear.

Deepak Sharma, Asst. Professor UPES Dehradun


Program of instance initializer block that is
invoked after super()
class A{
A(){ Note: Sequence of execution when an
System.out.println("parent class constructor invoked"); object is instantiated:
} • Memory for the object is allocated.
} • Any default values for the instance
variables are set.
class B2 extends A{
• The superclass's constructor is
B2(){ invoked.
super(); • The instance initializer block(s) are
System.out.println("child class constructor invoked"); executed in the order in which they
} appear in the class.
• The class's constructor is executed.
{System.out.println("instance initializer block is invoked");}

public static void main(String args[]){


B2 b=new B2();
}
}
Output:
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
 variable
 method
 Class
 The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized
final variable.
 It can be initialized in the constructor only.
 The blank final variable can be static also which will be initialized
in the static block only.
Deepak Sharma, Asst. Professor UPES Dehradun
Java final variable
 If you make any variable as final, you cannot change the value
of final variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class Output: Compile Time Error

Deepak Sharma, Asst. Professor UPES Dehradun


Java final method
 If you make any method as final, you cannot override it.

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
} Output: Compile Time Error
}

Deepak Sharma, Asst. Professor UPES Dehradun


Java final class
 If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

Output: Compile Time Error

Deepak Sharma, Asst. Professor UPES Dehradun


Is final method inherited?
 Yes, final method is inherited but you cannot
override it.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}

Can we declare a constructor final?


• No, because constructor is never inherited.

Deepak Sharma, Asst. Professor UPES Dehradun


Blank or uninitialized final variable
 A final variable that is not initialized at the time of declaration.
 If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed. (e.g. PAN Card Number)
 It can be initialized only in constructor.
class Student {
private String name;
private final String panCardNumber;

public Student(String name, String panCardNumber) {


this.name = name;
this.panCardNumber = panCardNumber;
}

public void displayDetails() {


System.out.println(name + " has PAN: " + panCardNumber);
}

public static void main(String[] args) {


Student deepak = new Student("Deepak", "XYZDE5678G");
deepak.displayDetails();
} Output:
Deepak has PAN: XYZDE5678G
}
static blank final variable
 A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can be
initialized only in static block.

class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}

Deepak Sharma, Asst. Professor UPES Dehradun


final parameter
 If you declare any parameter as final, you cannot change
the value of it.
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}

Deepak Sharma, Asst. Professor UPES Dehradun


Polymorphism in Java
 Polymorphism in Java is a concept by which we can perform
a single action in different ways.
 Types:
 compile-time polymorphism
 runtime polymorphism
 polymorphism in java is done by
 method overloading
 method overriding
 Compile time polymorphism
 Example- Overload a static method

Deepak Sharma, Asst. Professor UPES Dehradun


Runtime Polymorphism in Java
 Runtime polymorphism or Dynamic Method Dispatch is a
process in which a call to an overridden method is resolved at runtime
rather than compile-time.
 An overridden method is called through the reference variable of a
superclass.
 The determination of the method to be called is based on the object
being referred to by the reference variable.
 Since method invocation is determined by the JVM not compiler, it
is known as runtime polymorphism.

Deepak Sharma, Asst. Professor UPES Dehradun


Runtime Polymorphism
Upcasting
 If the reference variable of Parent class refers to the object of
Child class, it is known as upcasting.

class A{}
class B extends A{}
A a=new B();//upcasting

Deepak Sharma, Asst. Professor UPES Dehradun


Example of Java Runtime Polymorphism

class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
} Output:
running safely with 60km.

Deepak Sharma, Asst. Professor UPES Dehradun


class Bank{
Example
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
} Output:
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;} SBI Rate of Interest: 8.4
} ICICI Rate of Interest: 7.3
class AXIS extends Bank{ AXIS Rate of Interest: 9.7
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
} Deepak Sharma, Asst. Professor UPES Dehradun
Java Runtime Polymorphism with Data Member

 A method is overridden, not the data members, so runtime


polymorphism can't be achieved by data members.

class Bike{
int speedlimit=90;
} Output:
class Honda3 extends Bike{
int speedlimit=150; 90

public static void main(String args[]){


Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}

Deepak Sharma, Asst. Professor UPES Dehradun


Java Runtime Polymorphism with Multilevel
Inheritance
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
Output:
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
eating
Animal a1,a2,a3;
eating fruits
a1=new Animal();
drinking Milk
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
 There are two types of binding
 Static Binding (also known as Early Binding).
 Dynamic Binding (also known as Late Binding).

Deepak Sharma, Asst. Professor UPES Dehradun


Understanding Type
1) variables have a type
 Each variable has a type, it may be primitive and non-
primitive.
int data=30;
 Here data variable is a type of int.

2) References have a type


class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
} }
Deepak Sharma, Asst. Professor UPES Dehradun
Understanding Type
3) Objects have a type
An object is an instance of particular java class, but it is also an instance
of its superclass.

class Animal{}
class Dog extends Animal{
public static void main(String args[]){
Dog d1=new Dog();
} }

 Here d1 is an instance of Dog class, but it is also an instance of


Animal.

Deepak Sharma, Asst. Professor UPES Dehradun


static binding
 When type of the object is determined at compiled time(by the
compiler), it is known as static binding.
 If there is any private, final or static method in a class, there is static
binding.
Example of static binding

class Dog{
private void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Dog d1=new Dog();
d1.eat();
}
}

Deepak Sharma, Asst. Professor UPES Dehradun


Dynamic binding
 When type of the object is determined at run-time, it is known as
dynamic binding.
Example of dynamic binding
class Animal{ Output:dog is eating...
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
} • Object type cannot be determined by the compiler,
because the instance of Dog is also an instance of Animal.
• So compiler doesn't know its type, only its base type.

Deepak Sharma, Asst. Professor UPES Dehradun


instanceof operator
 The java instanceof operator is used to test whether the object is
an instance of the specified type (class or subclass or interface).
 The instanceof in java is also known as type comparison operator because
it compares the instance with type.
 It returns either true or false.
 If we apply the instanceof operator with any variable that has null
value, it returns false.
class Simple1{
public static void main(String args[]){ Output: true
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
instanceof operator
 An object of subclass type is also a type of parent class.
class Animal{}
class Dog extends Animal{//Dog inherits Animal Output:true

Note:
public static void main(String args[]){ Dog extends Animal therefore
Dog d=new Dog(); object of Dog can be referred by
System.out.println(d instanceof Animal);//true either Dog or Animal class.
}
}

 If we apply instanceof operator with a variable that have null value, it


returns false
class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}
Output: false
Deepak Sharma, Asst. Professor UPES Dehradun
Downcasting with java instanceof operator
 When Subclass type refers to the object of Parent class, it is known as
downcasting.
 If we perform it directly, compiler gives Compilation error.

Dog d=new Animal();//Compilation error

 If you perform it by typecasting, ClassCastException is thrown at


runtime. But if we use instanceof operator, downcasting is possible.

Dog d=(Dog)new Animal();


//Compiles successfully but ClassCastException is thrown at runtime

Deepak Sharma, Asst. Professor UPES Dehradun


Possibility of downcasting with instanceof
class Animal { }

class Dog3 extends Animal {


static void method(Animal a) {
if(a instanceof Dog3){
Dog3 d=(Dog3)a;//downcasting
System.out.println("ok downcasting performed");
}
} Output:
ok downcasting performed
public static void main (String [] args) {
Animal a=new Dog3();
Dog3.method(a);
}

Deepak Sharma, Asst. Professor UPES Dehradun


Downcasting without the use of instanceof

class Animal { }
class Dog4 extends Animal {
static void method(Animal a) {
Dog4 d=(Dog4)a;//downcasting
System.out.println("ok downcasting performed");
}
public static void main (String [] args) {
Output:
Animal a=new Dog4();
ok downcasting performed
Dog4.method(a);
}
}

Deepak Sharma, Asst. Professor UPES Dehradun


Abstraction in Java

 Abstraction is a process of hiding the implementation details and


showing only functionality to the user.
 Abstraction lets you focus on what the object does instead of how
it does it.

Ways to achieve Abstraction

• Abstract class (0 to 100%)

• Interface (100%)

Deepak Sharma, Asst. Professor UPES Dehradun


Abstract class
 A class which is declared with the abstract keyword is known as an
abstract class in Java.
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change
the body of the method.

abstract class A{}

Deepak Sharma, Asst. Professor UPES Dehradun


Abstract Method in Java
 A method which is declared as abstract and does not have
implementation is known as an abstract method.
abstract void printStatus();//no method body and abstract

abstract class Bike{


Abstract class that abstract void run();
has an abstract }
method. class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Rule: If there is an abstract method in a class, that class must be abstract.

Deepak Sharma, Asst. Professor UPES Dehradun


Example
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");} Output:
} drawing circle
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g.,
getShape() method
s.draw();
}
}

Deepak Sharma, Asst. Professor UPES Dehradun


Example
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;} Output:
} Rate of Interest is: 7 %
class PNB extends Bank{ Rate of Interest is: 8 %
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}

Deepak Sharma, Asst. Professor UPES Dehradun


Example
An abstract class can
//Example of an abstract class that has abstract and non-
have :
abstract methods
• data member
abstract class Bike{
• abstract method
Bike(){System.out.println("bike is created");}
• method body (non-
abstract void run();
abstract method)
void changeGear(){System.out.println("gear changed");}
• constructor
• even main() method
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-
Output:
abstract methods
bike is created
class TestAbstraction2{
running safely..
public static void main(String args[]){
gear changed
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
Example abstract class Animal {
abstract void makeSound();
public void eat() {
System.out.println("I can eat.");
}}

class Dog extends Animal {


// provide implementation of abstract method
public void makeSound() {
System.out.println("Bark bark");
Output: }}
Bark bark
I can eat. class Main {
public static void main(String[] args) {
// create an object of Dog class
Dog d1 = new Dog();
d1.makeSound();
d1.eat();

}}

Deepak Sharma, Asst. Professor UPES Dehradun


Abstract Class- Key Points
 We use the abstract keyword to create abstract classes and methods.
 An abstract method doesn't have any implementation (method body).
 A class containing abstract methods should also be abstract.
 We cannot create objects of an abstract class.
 To implement features of an abstract class, we inherit subclasses from it
and create objects of the subclass.
 A subclass must override all abstract methods of an abstract class.
However, if the subclass is declared abstract, it's not mandatory to override
abstract methods.
 We can access the static attributes and methods of an abstract class using
the reference of the abstract class. For example,
AbstractClass.staticMethod();

Deepak Sharma, Asst. Professor UPES Dehradun


Java Interface

 An interface in Java is a blueprint of a class.


 A Java interface is a collection of constants and abstract methods
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple
inheritance.
 Methods in an interface have public visibility by default

Deepak Sharma, Asst. Professor UPES Dehradun


Declaring Interface:
• An interface is declared by using the interface keyword.
• A class that implements an interface must implement all the methods
declared in the interface.
• Since Java 8, interface can have default and static methods which is
discussed later.
• The Java compiler adds public and abstract keywords before the
interface method. Moreover, it adds public, static and final keywords
before data members.

Deepak Sharma, Asst. Professor UPES Dehradun


The relationship between classes and
interfaces
 A class extends another class,
 An interface extends another interface,
 but a class implements an interface.

Deepak Sharma, Asst. Professor UPES Dehradun


Example

public interface Doable


{
public static final String NAME;

public void doThis();


public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}

Note: Like abstract classes, we cannot create objects of interfaces.

Deepak Sharma, Asst. Professor UPES Dehradun


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

Deepak Sharma, Asst. Professor UPES Dehradun


Example
//Interface declaration: by first user
interface Drawable{ Output:
void draw();
} drawing circle
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g.
getDrawable()
d.draw();
}}

Deepak Sharma, Asst. Professor UPES Dehradun


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

Deepak Sharma, Asst. Professor UPES Dehradun


Multiple inheritance in Java by interface
 If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.

Deepak Sharma, Asst. Professor UPES Dehradun


Multiple inheritance using Interfaces
interface Printable{
void print(); Output:Hello
} Welcome
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();
}
}

Deepak Sharma, Asst. Professor UPES Dehradun


Q) Multiple inheritance is not supported through class in java, but it
is possible by an interface, why?
 There is no ambiguity if implementation is provided by the
implementation class.
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
Interface inheritance
 A class implements an interface, but one interface extends another
interface.
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
Deepak Sharma, Asst. Professor UPES Dehradun
Java 8 Default Method in Interface
 Since Java 8, we can have method body in interface. But we
need to make it default method.
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw(); Output:
d.msg();
}} drawing rectangle
default method
Deepak Sharma, Asst. Professor UPES Dehradun
Java 8 Static Method in Interface
 Since Java 8, we can have static method in interface.

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle(); Output:
d.draw(); drawing rectangle
System.out.println(Drawable.cube(3)); 27
}

Deepak Sharma, Asst. Professor UPES Dehradun


What is marker or tagged interface?
 An interface which has no member is known as a marker or
tagged interface, for example, Serializable, Cloneable, Remote,
etc.
 They are used to provide some essential information to the JVM
so that JVM may perform some useful operation.

//How Serializable interface is written?


public interface Serializable{
}

Deepak Sharma, Asst. Professor UPES Dehradun


Difference between abstract class and interface

 Abstract class and interface both are used to achieve abstraction


where we can declare the abstract methods. Abstract class and
interface both can't be instantiated.

Deepak Sharma, Asst. Professor UPES Dehradun


Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. 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, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class An interface can extend another Java interface only.
and implement multiple Java interfaces.

7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Deepak Sharma, Asst. Professor UPES Dehradun


Encapsulation in Java
 Encapsulation in Java is a process of wrapping code and data
together into a single unit, for example, a capsule which is mixed of
several medicines.
 We can create a fully encapsulated class in Java by making all the
data members of the class private. Now we can use setter and
getter methods to set and get the data in it.

Deepak Sharma, Asst. Professor UPES Dehradun


Advantage of Encapsulation in Java
 By providing only a setter or getter method, you can make the
class read-only or write-only. In other words, you can skip the
getter or setter methods.
 It provides you the control over the data. Suppose you want to set
the value of id which should be greater than 100 only, you can write
the logic inside the setter method.You can write the logic not to store
the negative numbers in the setter methods.
 It is a way to achieve data hiding in Java because other class will not
be able to access the data through the private data members.
 The encapsulate class is easy to test. So, it is better for unit testing.
 The standard IDE's are providing the facility to generate the getters
and setters. So, it is easy and fast to create an encapsulated
class in Java.
Deepak Sharma, Asst. Professor UPES Dehradun
Example- 1
//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
package pack;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name; Go to Next Slide to
} test encapsulation
//setter method for name
public void setName(String name){
this.name=name
}
}
Deepak Sharma, Asst. Professor UPES Dehradun
Example-1 Cont..
//A Java class to test the encapsulated class.
package pack;
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}

Deepak Sharma, Asst. Professor UPES Dehradun


Read-Only class
//A Java class which has only getter methods.
public class Student{
//private data member
private String college=“UPES";
//getter method for college
public String getCollege(){
return college;
}
}

Now, you can't change the value of the college data member which is “UPES".
s.setCollege(“UPES DDN");//will render compile time error

Deepak Sharma, Asst. Professor UPES Dehradun


Write-Only class
//A Java class which has only setter methods.
public class Student{
//private data member
private String college;
//getter method for college
public void setCollege(String college){
this.college=college;
}
}

Now, you can't get the value of the college, you can only change the value of
college data member.

System.out.println(s.getCollege());//Compile Time Error, because there is no


such method

System.out.println(s.college);//Compile Time Error, because the college data


member is private.
//So, it can't be accessed from outside the class
Deepak Sharma, Asst. Professor UPES Dehradun
/A Account class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
class Account {
//private data members
private long acc_no;
private String name,email;
private float amount;
//public getter and setter methods
public long getAcc_no() {
return acc_no;
public void setEmail(String email) {
}
this.email = email;
public void setAcc_no(long acc_no) {
}
this.acc_no = acc_no;
public float getAmount() {
}
return amount;
public String getName() {
}
return name;
public void setAmount(float amount) {
}
this.amount = amount;
public void setName(String name) {
}
this.name = name;
}
}
public String getEmail() {
return email; Go to Next Slide to test the
} Deepak Sharma, Asst. Professor UPES Dehradun Account Class
/A Java class to test the encapsulated class Account.
public class TestEncapsulation {
public static void main(String[] args) {
//creating instance of Account class
Account acc=new Account();
//setting values through setter methods
acc.setAcc_no(7560504000L);
acc.setName("Sonoo Jaiswal");
acc.setEmail("[email protected]");
acc.setAmount(500000f);
//getting values through getter methods
System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+"
"+acc.getAmount());
}
}

Output:

7560504000 Sonoo Jaiswal [email protected] 500000.0

Deepak Sharma, Asst. Professor UPES Dehradun

You might also like