0% found this document useful (0 votes)
5 views

Lecture Slide - Week 5

The document provides an overview of method overriding in Java, explaining its purpose, rules, and usage in achieving runtime polymorphism. It also discusses the super keyword, its applications for accessing parent class members, and constructor chaining. Additionally, the document outlines different types of inheritance in Java, including single, multilevel, hierarchical, and the reasons why multiple inheritance is not supported.

Uploaded by

guptanaman1006
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)
5 views

Lecture Slide - Week 5

The document provides an overview of method overriding in Java, explaining its purpose, rules, and usage in achieving runtime polymorphism. It also discusses the super keyword, its applications for accessing parent class members, and constructor chaining. Additionally, the document outlines different types of inheritance in Java, including single, multilevel, hierarchical, and the reasons why multiple inheritance is not supported.

Uploaded by

guptanaman1006
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/ 146

OBJECT ORIENTED

PROGRAMMING
USING JAVA
 Method Overriding

OUTLINE  Super Keyword


 Types of Inheritance
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 Overriding
• 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 METHOD OVERRIDING

• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
EXAMPLE OF METHOD OVERRIDING
//Creating a parent class.
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
}
}
EXAMPLE OF METHOD OVERRIDING
//Creating a parent class.
o/p:
class Vehicle{
Bike is Running Safely
//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
}
}
Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However,
the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%,
7%, and 9% rate of interest.

EXAMPLE OF METHOD OVERRIDING


A REAL EXAMPLE OF METHOD OVERRIDING
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}}
//Creating child classes.
class SBI extends Bank{ o/p:
int getRateOfInterest(){return 8;} } SBI Rate of Interest:8
class ICICI extends Bank{ ICICI Rate of Interest:7
int getRateOfInterest(){return 7;} } AXIS Rate of Interest:9
class AXIS extends Bank{
int getRateOfInterest(){return 9;} }
//Test class to create objects and call the methods
class Test2{
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());
} }
PROBLEM DESCRIPTION: NEED OF SUPER KEYWORD
PROBLEM DESCRIPTION: NEED OF SUPER KEYWORD

Step:1
null

obj
Step:2 a=0
b=0
c=0
obj Child object
Step:3
a=10
b=100
c=0
obj
Child object

Step:4 a=200
b=20
c=220
obj
Child object
PROBLEM DESCRIPTION: NEED OF SUPER KEYWORD

O/P:
Parent first10100
Child second20020
Sum is 220
PROBLEM DESCRIPTION: NEED OF SUPER KEYWORD

Output

super.a executes parent class variable which is


a=10;
THE SUPER KEYWORD

• It is used to differentiate the members of superclass (immediate parent) from the


members of subclass, if they have same names.

• super can be used to refer immediate parent class instance variable.


• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
SUPER CAN BE USED TO INVOKE PARENT CLASS VARIABLE

• The first form of super acts somewhat like this, except that it always refers to
the immediate superclass variables of the subclass in which it is used.

• This usage has the following general form:

super.variable
SUPER CAN BE USED TO INVOKE PARENT CLASS VARIABLE
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 TestSuper1{ //class with a main method
public static void main(String args[]){

Dog d=new Dog(); //object of sub class


d.printColor();
}}
SUPER CAN BE USED TO INVOKE PARENT CLASS VARIABLE
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
}

} Output:
class TestSuper1{ //class with a main method
black
public static void main(String args[]){ white
Dog d=new Dog(); //object of sub class
d.printColor();
}}
SUPER CAN BE USED TO INVOKE PARENT CLASS METHOD

• The second form of super acts somewhat like this, except that it always refers to the
immediate superclass method of the subclass in which it is used.
• This usage has the following general form:

super.method()
SUPER CAN BE USED TO INVOKE PARENT CLASS METHOD
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 TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
SUPER CAN BE USED TO INVOKE PARENT CLASS METHOD
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(){
Output
super.eat();
bark();
}
eating...
} barking...
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
USING SUPER TO CALL SUPERCLASS CONSTRUCTORS

• A subclass can call a constructor defined by its superclass by use of the following
form of super:
super(arg-list);
• Here , arg-list specifies any arguments needed by the constructor in the
superclass.super( )
• It always be the first statement executed inside a subclass constructor.
• When a subclass calls super(), it is calling the constructor of its immediate
superclass. Thus , super() always refers to the superclass immediately above the
calling class.
USING SUPER TO CALL SUPERCLASS CONSTRUCTORS
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super(); //first statement
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
USING SUPERTO CALL SUPERCLASS CONSTRUCTORS
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){ Output
super(); //first statement
System.out.println("dog is created");
animal is created
}
dog is created
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
NOTE:

• Call to super() must be first statement in Derived(Student) Class constructor.


• If a constructor does not explicitly invoke a superclass constructor, the Java
compiler automatically inserts a call to the no-argument constructor of the
superclass. If the superclass does not have a no-argument constructor, you will get
a compile-time error. Object does have such a constructor, so if Object is the only
superclass, there is no problem.
• If a subclass constructor invokes a constructor of its superclass, either explicitly or
implicitly, you might think that a whole chain of constructors called, all the way
back to the constructor of Object. This, in fact, is the case. It is called constructor
chaining..
TYPES OF INHERITANCE IN JAVA

There are four types of inheritance in java:


1) Single
2) Multilevel and
3) Hierarchical.
4) Hybrid

In java programming, multiple and hybrid inheritance is supported through interface only.
TYPES OF INHERITANCE IN JAVA
SINGLE INHERITANCE
class Animal
{
void eat()
{System.out.println("eating...");}
}
Note: When a class inherits another class, it is
class Dog extends Animal{ known as a single inheritance. In the example
void bark() given below, Dog class inherits the Animal
{System.out.println("barking...");} class, so there is the single inheritance.
}

class TestInheritance{
public static void main(String args[]){ Dog d=new
Dog();
d.bark();
d.eat();
}}
MULTILEVEL INHERITANCE

class Animal{
void eat() When there is a chain of inheritance, it is
{System.out.println("eating...");} known as multilevel inheritance. As you can
} see in the example given below, BabyDog class
class Dog extends Animal{ inherits the Dog class which again inherits the
void bark() Animal class, so there is a multilevel
{System.out.println("barking...");} inheritance.
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
MULTILEVEL INHERITANCE

class Animal{
void eat() When there is a chain of inheritance, it is
{System.out.println("eating...");} known as multilevel inheritance. As you can
} see in the example given below, BabyDog class
class Dog extends Animal{ inherits the Dog class which again inherits the
void bark() Animal class, so there is a multilevel
{System.out.println("barking...");} inheritance.
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{ OUTPUT:
public static void main(String args[]){
BabyDog d=new BabyDog(); weeping...
d.weep(); barking...
d.bark(); eating...
d.eat();
}
}
HIERARCHICAL INHERITANCE
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
When two or more classes inherits a single
void bark()
class, it is known as hierarchical inheritance.
{System.out.println("barking...");}
In the example given below, Dog and Cat
}
classes inherits the Animal class, so there is
class Cat extends Animal{
hierarchical inheritance.
void meow()
{System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
HIERARCHICAL INHERITANCE
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
When two or more classes inherits a single
void bark()
class, it is known as hierarchical inheritance.
{System.out.println("barking...");}
In the example given below, Dog and Cat
}
classes inherits the Animal class, so there is
class Cat extends Animal{
hierarchical inheritance.
void meow()
{System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){ OUTPUT
Cat c=new Cat(); meowing...
c.meow(); eating...
c.eat();
//c.bark();//C.T.Error
}}
MULTIPLE INHERITANCE

When a class extends multiple classes i.e., known as multiple inheritance. For Example:

It is not allowed in Java through


extends
WHY MULTIPLE INHERITANCE IS NOT SUPPORTED IN JAVA?

• Consider a scenario where A, B and C are three classes. The C class inherits A
and B classes. If A and B classes have same method and you call it from child
class object.
• There will be ambiguity to call method of A or B class.
WHY MULTIPLE INHERITANCE IS NOT SUPPORTED IN JAVA?
class A{
void add()
{a =10;
b=5;

c=a+b;} }
class B{
void add()
{a =10;
b=5;
c=15;

d=a+b+c;}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){

C obj=new C();
obj.add();//Now which add() method would be invoked?
} }
WHY MULTIPLE INHERITANCE IS NOT SUPPORTED IN JAVA?

• To reduce the complexity and


• simplify the language,
multiple inheritance is not supported in java.
• Since compile time errors are better than runtime errors,
• java renders compile time error if you inherit 2 classes.

• So whether you have same method or different, there will be compile time error
now.
• Therefore, Inheritance is called Compile Time Mechanism.
class A{
void add()
{a =10;
b=5;
c=a+b;}
}
class B{
Output:
void sub()
'{' expected
{
class C extendsA,B
a =10;
b=5;
c= a-b;
}
class C extends A,B{
Public Static void main(String args[]){
C obj=new C();
obj.add();
}
}
Overloading vs. Overriding

Overloading deals with Overriding deals with two


multiple methods in the methods, one in a parent
same class with the class and one in a child
same name but class, that have the same
different signatures signature

Overloading lets you Overriding lets you define


define a similar a similar operation in
operation in different different ways for
ways for different data different object types
Controlling Inheritance

Visibility modifiers determine which class members are accessible and which
are not.

Members (variables and methods) declared with public visibility are


accessible, and those with private visibility are not.

Problem: How to make class/instance variables visible only to its subclasses?


Solution: Java provides a third visibility modifier that helps in inheritance
situations: protected

37
The protected Modifier

The protected visibility modifier allows a member of a


base class to be accessed in the child
protected visibility provides more encapsulation than public
does
protected visibility is not as tightly encapsulated as private
visibility
Book
protected int pages
All these methods can access + getPages() : int
the pages instance variable. + setPages(): void

Note that by constructor Dictionary


chaining rules, pages is an
instance variable of every + getDefinitions() : int
+ setDefinitions(): void
object of class Dictionary. + computeRatios() : double
38
FINAL
• It is the modifier applicable for classes, methods and variables.
• If a method declared as the final then we are not allowed to override that method in the child
class.
• Whatever the methods parent has by default available to the child.
Methods • If the child is not allowed to override any method,that method we have to declare with
final in parent class.That is final methods cannot overridden.

• If a class declared as the final then we can't creates the child class that is
Class
inheritance concept is not applicable for final classes.

• If a variable declared as the final then we need to look for the type of variables
Variables
and then correspondingly actions need to be taken (discussed later in the slides).
EXAMPLE
final classTest
{
void methodOne( )
{
System.out.println(“Protected Member Access Modifier”);
}
}
classTest1 extendsTest
{ public static void main(String args[])
{
Test t=newTest();
Every method present inside a final class is always final t.methodOne();
Test1 b = newTest1();
by default whether we are declaring or not. But every b.methodOne();
variable present inside a final class need not be final. Test c = newTest1();
c.methodOne();
}
}
FINAL VARIABLES IN INSTANCE VARIABLES

• If the value of a variable is varied from object to object such type of variables are
called instance variables.
• For every object a separate copy of instance variables will be created.

• For the instance variables it is not required to perform initialization explicitly jvm will
always provide default values.
FINAL VARIABLES IN INSTANCE VARIABLES

• If the instance variable declared as the final compulsory we should perform


initialization explicitly and JVM won't provide any default values. whether we are
using or not otherwise we will get compile time error.
classTest classTest
{ {
int i; final int i;
} }

• For the final instance variables we should perform initialization before constructor
completion. That is the following are various possible places for this.
• Initialization while declaration, instance initialization block, and constructor.
FINAL VARIABLES IN STATIC VARIABLES

• If the static variable declare as final then compulsory we should perform initialization
explicitly whether we are using or not otherwise we will get compile time error.(The
JVM won't provide any default values)

• For the final static variables we should perform initialization before class loading
completion otherwise we will get compile time error. That is the following are
possible places.
• Initialization while declaration and inside static block.
FINAL VARIABLES IN LOCAL VARIABLES

• To meet temporary requirement of the Programmer sometime we can declare the


variable inside a method or block or constructor such type of variables are called local
variables.
• For the local variables jvm won't provide any default value compulsory we should
perform initialization explicitly before using that variable.
• The only applicable modifier for local variables is final if we are using any other
modifier we will get compile time error.
classTest
{
public static void main(String [] args) {
final int i;
System.out.println(“Bennett”);
}
}
FINAL VARIABLES IN LOCAL VARIABLES
 Abstraction

OUTLINE  Abstract Method


 Abstract Class
ABSTRACTION IN JAVA

• Abstraction is a process of hiding the implementation details and showing only


functionality to the user.
• The extent to which a module hides its internal data and other implementation
details from the other modules is the most important factor that distinguishes a
well-designed Object-Oriented module from other modules.
• It shows only important things to the user and hides the internal details.
• This is basically called Abstraction in which the complex details are being
hidden from the users.
EXAMPLE:

• Consider the example of an email, the user does not know about the complex
details such as what happens just after sending an email, which protocol is used by
the server to send the message. Therefore, we just need to mention the address of the
receiver, type the content and click the send button.
• For example sending sms, you just type the text and send the message. You don't
know the internal processing about the message delivery.
HOWTOACHIEVEABSTRACTION IN JAVA?

There are two ways to achieve abstraction in java:

• Abstract class (0 to 100%). (partial to complete abstraction)


--abstract classes can contain concrete methods that have the
implementation which results in a partial abstraction.

• Interface (100% (complete abstraction)).


--Interfaces allow you to abstract the implementation completely.
ABSTRACT KEYWORD

• Abstract is a keyword which means not complete / partial implementation)


(having only declaration not definition)
• It is applicable for Method , class but not on variable.
ABSTRACT METHOD

• Abstract methods are methods with no implementation and without a method body.
They do not contain any method statement.
• An abstract method is declared with an abstract keyword.
• The declaration of an abstract method must end with a semicolon ;
• The child classes which inherit the abstract class must provide the implementation of
these inherited abstract methods.

access-specifier abstract return-type method-name();


For ex: public abstract int myMethod(int n1, int n2); // no body
NEED OF ABSTRACT METHOD

Don’t know
Public class covid19 implementa
{ tion Public abstract class covid19 Abstract
Public void vaccine () { Methods are
{ Public abstract void vaccine (); implemented in
} // ends with ; the child class
} Know // no cur
} only
declaration
WHICH ONE IS VALID?

• public abstract void m1(){}


• public void m1();
• public abstract void m1();
• public void m1(){}
WHICH ONE IS VALID?

• public abstract void m1(){} // compilation error: abstract method cannot have a body
• public void m1(); // compilation error: missing method body or abstract method
• public abstract void m1();
• public void m1(){}
ABSTRACT CLASS
• A class which contains the abstract keyword in its declaration is known as abstract class.
• an abstract class is like a guideline or a template that has to be extended by its child classes for the
implementation.
• Need of Abstract class: Sometimes implementation of a class is not complete or having partial
implementation.
•Abstract classes may or may not contain abstract methods, i.e., methods without body (
public void get(); )
• But, if a class has at least one abstract method, then the class must be declared abstract.
• If a class is declared abstract, it cannot be instantiated.
• To use an abstract class, you have to inherit it from another class, provide implementations to the abstract
methods in it.
• If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
CASE 1: CASE 1 & 2
public class Main
{
abstract void wheel();
public static void main(String[] args) {
System.out.println("Hello World");
Main m =new Main(); CASE 2:

}
} abstract public class Main
{
} abstract void wheel();
public static void main(String[] args) {
System.out.println("Hello World");
Main m =new Main();
}

}
CASE 1: CASE 1 & 2
public class Main Output
{
abstract void wheel(); Main.java:9:error:Mainisnotabstractanddoesnotoverrideabstractmethodwhe
public static void main(String[] args) { el()inMain
System.out.println("Hello World");
Main m =new Main(); CASE 2:

}
} abstract public class Main
{
} abstract void wheel();
public static void main(String[] args) {
System.out.println("Hello World");
Output Main m =new Main();
}
Main.java:14: error: Main is abstract; cannot be instantiated
}
CONSIDERA SCENARIOTHATYOU HAVETO BUILDYOUR FINALYEAR
PROJECT

• You want to make a new mobile app with some different features.
• You want to add features like
• Calling
• Moving
• Video Calling
PROGRAM

class FirstYear public class ABC {


{ public static void main(String args[])
public void calling() {
{ FirstYear b = new FirstYear();
System.out.println("Calling"); b.calling();
} }
public void moving();
}
public void videocaling();
}
PROGRAM

abstract class FirstYear public class ABC {


{ public static void main(String args[])
public void calling() {
{
System.out.println("Calling");
//FirstYear b = new FirstYear();
} //b.calling(); { we can’t create
public abstract void moving(); public abstract void the object of abstract class}
videocaling(); }
} }
PROGRAM
abstract class FirstYear public class ABC {
{ public static void main(String args[]) {
public void calling() SecondYear b = new SecondYear();
{ b.calling();
System.out.println("Calling"); }
} }
public abstract void moving();
public abstract void videocaling();
}
Class SecondYear extends FirstYear{
public void moving()
{System.out.println("Calling");}}
PROGRAM
abstract class FirstYear
{
public class ABC {
public void calling()
public static void main(String args[]) {
{
//SecondYear b = new SecondYear();
System.out.println("Calling");
//b.calling(); { we can’t create the
} object of abstract class}
public abstract void moving(); }
public abstract void videocaling(); }
}
abstract Class SecondYear extends FirstYear{
public void moving()
{System.out.println("Calling");}}
abstract class FirstYear PROGRAM Class ThirdYear extends SecondYear{
{ Public void videocaling()
public void calling() {System.out.println(“Video Call");
{ }
System.out.println("Calling"); public class ABC {
} public static void main(String args[])
public abstract void moving(); ThirdYear b = new ThirdYear();
public abstract void videocaling(); b.calling();
} b.moving();
abstract Class SecondYear extends FirstYear{ b.videocaling();
public void moving() }
{System.out.println("Calling");}} }
ABSTRACT CLASS VS ABSTRACT METHODS

• If a class contain at least one abstract method compulsory we have to declare


that class as a abstract class.
• Even if class does not contain abstract method still we can declare a class as
abstract class
CASE 3
abstract public class Main
{
abstract void wheel();
abstract void engine();
public static void main(String[] args) {
System.out.println("Hello World");
// Main m =new Main();
}

class main2 extends Main


{

Main.java:20: error: main2 is not abstract and does not override abstract
method engine() in Main
CASE 4
abstract public class Main
{
abstract void wheel();
abstract void engine();
public static void main(String[] args) {
System.out.println("Hello World");
//Main m =new Main();
}

abstract class main2 extends Main


{

OUTPUT
Hello World
CASE 5
abstract public class Main
{
abstract void wheel();
abstract void engine();
public static void main(String[] args) {
System.out.println("Hello World");
// Main m =new Main();
}
}

class main2 extends Main


{
void wheel(){}
}

OUTPUT
Main.java:20: error: main2 is not abstract and does not override abstract
method engine() in Main
AN ABSTRACT CLASS CAN HAVE A CONSTRUCTOR BUT CAN NOT
CREATE AN OBJECT.
public class child1 extends parent{
public abstract class parent{ Int m;
Int i; Int n;
Int j; Public child1 (int i, int j, int m, int n)
{
} this.i=i;
this.j=j;
this.m=m;
this.n=n;
}
public static void main(String[] args) {
Child1 c=new child1(1,2,3,4);
}
}
AN ABSTRACT CLASS CAN HAVE A CONSTRUCTOR BUT CAN NOT
CREATE AN OBJECT.
public class child1 extends parent{ class child2 extends parent{
abstract class parent{ Int m;
Int i; Int x;
Int n; Int y;
Int j; Public child1 (int i, int j, int m, int n) Public child1 (int i, int j, int x, int y)
{ {
} this.i=i; this.i=i;
this.j=j; this.j=j;
this.m=m; this.x=x;
this.n=n; this.y=y;
} }
public static void main(String[] args) {
Child1 c=new child1(1,2,3,4);
}
}

• Duplicate code
• Waste a lot of time
AN ABSTRACT CLASS CAN HAVE A CONSTRUCTOR BUT CAN NOT
CREATE AN OBJECT. (SOLUTION)
public abstract class parent{ public class child1 extends parent{
Int i; Int m; public class child2 extends parent{
Int j; Int n; Int x;
Public parent (int i, int j) Public child1 (int i, int j, int m, int n) Int y;
{ { Public child2 (int i, int j, int x, int y)
this.i=i; super(i,j); {
this.j=j this.m=m; super(i,j);
} this.n=n; this.x=x;
} this.y=y;
public static void main(String[] args) { }
Child1 c=new child1(1,2,3,4);
}
}
MCQ

• Abstract class A has 4 virtual functions. Abstract class B defines only 2 of those
member functions as it extends class A. Class C extends class B and
implements the other two member functions of class A. Choose the correct
option below.
1. Program won’t run as all the methods are not defined by B
2. Program won’t run as C is not inheriting A directly
3. Program won’t run as multiple inheritance is used
4. Program runs correctly
MCQ

• Abstract class A has 4 virtual functions. Abstract class B defines only 2 of those
member functions as it extends class A. Class C extends class B and
implements the other two member functions of class A. Choose the correct
option below.
1. Program won’t run as all the methods are not defined by B
2. Program won’t run as C is not inheriting A directly
3. Program won’t run as multiple inheritance is used
4. Program runs correctly
Abstract Classes
Java allows abstract classes
use the modifier abstract on a class header to declare an abstract
class
abstract class Vehicle
{ … }
An abstract class is a placeholder in a class hierarchy that
represents a generic concept

Vehicle

Car Boat Plane


74
Abstract Class: Example
 An abstract class often contains abstract
methods, though it doesn’t have to
 Abstract methods consist of only methods declarations,
without any method body

public abstract class Vehicle


{
String name;

public String getName()


{ return name; } \\ method body

abstract public void move();


\\ no body!
}

75
Abstract Classes
An abstract class often contains abstract methods, though it
doesn’t have to
Abstract methods consist of only methods declarations, without any
method body

The non-abstract child of an abstract class must override the


abstract methods of the parent
An abstract class cannot be instantiated
(why?)

The use of abstract classes is a design decision; it helps us


establish common elements in a class that is too general to
instantiate

76
What is Abstract Class

In C++, if a class has at least one pure virtual function,


then the class becomes abstract. Unlike C++, in Java,
separate keyword abstract is used to make a class
abstract.

abstract class Shape {


int color;
// An abstract function
abstract void draw();
}

77
Important Point About Abstract Class

•An instance of an abstract class can not be created.


•Constructors are allowed.
•We can have an abstract class without any abstract
method.
•Abstract classes can not have final methods because
when you make a method final you can not override it
but the abstract methods are meant for overriding.
•We are not allowed to create object for any abstract
class.
•We can define static methods in an abstract class

78
Example

abstract class Base {


abstract void fun();
}

// Class 2
class Derived extends Base {
void fun()
{
System.out.println("Derived fun() called");
}
}

79
Cont..
// Class 3
// Main class
class Main {
// Main driver method
public static void main(String args[])
{
// We can have references of Base type.
Base b = new Derived();
b.fun();
}
}

80
Example

abstract class Base {


// Constructor of class 1
Base()
{
// Print statement
System.out.println("Base Constructor Called");
}
// Abstract method inside class1
abstract void fun();
}

81
Cont..

class Derived extends Base {


// Constructor of class2
Derived()
{
System.out.println("Derived Constructor Called");
}
// Method of class2
void fun()
{
System.out.println("Derived fun() called");
}
}
82
Cont..

class Main {

// Main driver method


public static void main(String args[])
{
// Creating object of class 2
// inside main() method
Derived d = new Derived();
}
}

83
Example 3
abstract class Base {

// Demo method
void fun()
{
// Print message if class 1 function is called
System.out.println(
"Function of Base class is called");
}
}

84
Cont..
Class Derived extend Base {} //class 2
class Main {
// Main driver method
public static void main(String args[])
{
// Creating object of class 2
Derived d = new Derived();
// Calling function defined in class 1 inside main()
// with object of class 2 inside main() method
d.fun();
}
}
85
Abstract Classes Can Also Have final Methods

abstract class Base {

final void fun()


{
System.out.println("Base fun() called");
}
}
// Class 2
class Derived extends Base {
}
86
Cont..

// Class 3 // Main class


class Main {
// Main driver method
public static void main(String args[])
{
// Creating object of abstract class
Base b = new Derived();
// Calling method on object created above
// inside main()
b.fun();
}
87
}
We can define static methods in an
abstract class that can be called
independently without an object.
abstract class Helper {

// Abstract method
static void demofun()
{

// Print statement
System.out.println("Geeks for Geeks");
}
88
}
Cont..

// Main class extending Helper class


public class GFG extends Helper {

// Main driver method


public static void main(String[] args)
{
// Calling method inside main()
// as defined in above class
Helper.demofun();
}
}
89
Questions

What is Abstraction in Java?


Abstraction in Java is a technique by which we can hide the data that is not required to users. It hides all unwanted data
so that users can work only with the required data

90
2
How to achieve or implement Abstraction in Java?
There are two ways to implement abstraction in java. They are as follows:
a) Abstract class (0 to 100%)
b) Interface (100%)

91
3

What is Abstract class in Java? How to define it?


An abstract class in java is a class that is declared with an abstract keyword.
Example of Abstract class:
abstract class test {
abstract void display();
}

92
4

What is the difference between abstract class and concrete class?


We cannot create an object of abstract class. Only objects of its non-abstract (or concrete)
sub classes can be created.
It can have zero or more abstract methods that are not allowed in a non-abstract class
(concrete class).

93
5
What is Abstract in Java?
Abstract is a non-access modifier in java that is applicable for classes, interfaces, methods, and inner classes.

94
6
What is Abstract method in Java?
A method which is declared with abstract modifier and has no implementation (means no body) is called abstract
method in java.
It does not contain any body. It has simply a signature declaration followed by a semicolon

95
7

Can an abstract method be declared as static?


No

96
8
Can an abstract method be declared with private modifier?
No, it cannot be private because the abstract method must be implemented in the child class. If we declare it as private,
we cannot implement it from outside the class.

97
9

What is Concrete method in Java?


A concrete method in Java is a method which has always the body. It is also called a complete method in java.

98
10.

When to use Abstract class in Java?


An abstract class can be used when we need to share the same method to all non-abstract sub classes with their own
specific implementations

99
11
Is it possible to create an object of abstract class in Java?
No. It is not possible but we can create an object of its subclass.

10
12

Is it possible that an abstract class can have without any abstract method?
Yes

10
13,14,15
Can an abstract class have constructor?
Yes.
17. Is abstract class allow to define private, final, static, and concrete methods?
Yes.
18. Is it possible to achieve multiple inheritance through abstract class?
No.

10
16
Can we define an abstract method inside non-abstract class (concrete class)?
No, we cannot define an abstract method in non-abstract class.

10
17

What will happen if we do not override all abstract methods in subclass?


Java compiler will generate compile time error. We will have to override all abstract methods in subclass.

10
18

What is the difference between Abstraction and Encapsulation?


Abstraction hides the implementation details from users whereas, encapsulation wraps (binds) data and code into a
single unit

10
19
Why abstract class has constructor even though you cannot
create object?
We cannot create an object of abstract class but we can create
an object of subclass of abstract class. When we create an
object of subclass of an abstract class, it calls the constructor of
subclass.
This subclass constructor has a super keyword in the first line
that calls constructor of an abstract class. Thus, the constructors
of an abstract class are used from constructor of its subclass.
If the abstract class doesn’t have constructor, a class that
extends that abstract class will not get compiled.
10
20

Why should we create reference to superclass (abstract class


reference)?
We should create a reference of the superclass to access
subclass features because superclass reference allows only to
access those features of subclass which have already declared in
superclass.
If you create an individual method in subclass, the superclass
reference cannot access that method. Thus, any programmer
cannot add their own additional features in subclasses other
than whatever is given in superclass.

10
21

What is the advantage of Abstract class in Java?


•Abstract class makes programming better and more
flexible by giving the scope of implementing abstract
methods.
•Programmer can implement abstract method to perform
different tasks depending on the need.
•We can easily manage code.

10
Single vs. Multiple Inheritance

Some object-oriented languages allow multiple inheritance,


which allows a class to be derived from two or more classes,
inheriting the members of all parents
The price: collisions, such as the same variable name, same
method name in two parents, have to be resolved
Java decision: single inheritance, meaning that a derived class
can have only one parent class

109
Interface

Java does not support multiple inheritance.


In other words, classes in Java cannot have more than one
super class.
For example, a definition like
class One extends Two, Three
{ …………………… }
is not permitted in Java.
However, Java provides an alternate approach known as
interfaces to support the concept of multiple inheritance.

11
Interface
An interface is a reference type in Java. It is
similar to class. It is a collection of abstract
methods.
An Interface in Java programming language is
defined as an abstract type used to specify the
behavior of a class. An interface in Java is a
blueprint of a class. A Java interface contains
static constants and abstract methods.

11
Interface
An interface is basically a kind of class.
Like classes, interfaces contain methods and
variables but with a major difference.
The difference is that interfaces define only
abstract methods and final fields.
This means that interfaces do not specify any code
to implement these methods and data fields
contain only constants.
Therefore, it is the responsibility of the class that
implements an interface to define the code for
implementation of these methods.

11
Cont..

•An Interface is about capabilities like a Player may be an


interface and any class implementing Player must be able
to (or must implement) move(). So, it specifies a set of
methods that the class has to implement.
•If a class implements an interface and does not provide
method bodies for all functions specified in the interface,
then the class must be declared abstract.

11
Syntax

interface {
// declare constant fields
// declare methods that abstract // by default.
}
To declare an interface, use the interface keyword. It is used
to provide total abstraction. That means all the methods in an
interface are declared with an empty body and are public and
all fields are public, static, and final by default. A class that
implements an interface must implement all the methods
declared in the interface. To implement interface use
implements keyword.
11
Cont..
Why use interfaces when we have abstract classes?
The reason is, abstract classes may contain non-
final variables, whereas variables in the interface
are final, public and static.

11
Class Vs Interface

S. N. Class Interface

In an interface, you can’t


In class, you can instantiate variables and
1. instantiate variables and create an
create an object.
object.

The interface cannot contain


Class can contain concrete(with
2. concrete(with implementation)
implementation) methods
methods

The access specifiers used with classes In Interface only one specifier is
3.
are private, protected, and public. used- Public.

An interface does not contain any


Contain constructor constructors.
4
No abstract method All the methods in an interface are
abstract.
11
Example
interface Itface
{ static final int i = 100 ;
static final String name = new
String(“Gautam”) ;
void display( ) ;
}
Note that the code for the method is not included in the
interface and the method declaration simply ends with a
semicolon.
The class that implements this interface must define the code
for the method.
11
Extending Interfaces
Like classes, interfaces can also be extended.
That is, an interface can be sub interfaced from other
interfaces.
The new sub interface will inherit all the members of the
super interface in the manner similar to sub classes.
This is achieved using the keyword extends as shown
below:
interface name2 extends name1
{
body of name2
}

11
Example
Interface animal
{
public void eat();
public void travel();
}

Save As animal.java

11
Cont..
Public class mint implements animal {
Public void eat() {
System.out.println(“Mammal eats”);
}
Public void travel() {
System.out.println(“Mammal travels”);
}
Public void nooflegs() {
return 0;
}

12
Cont..
public static void main(String args[]){
mint obj=new mint();
obj.eat();
obj.travel();
}
}

12
Advantages of Interfaces in Java
•Without bothering about the implementation part,
we can achieve the security of the
implementation.
•In Java, multiple inheritance is not allowed,
however, you can use an interface to make use of
it as you can implement more than one interface.

12
Important Points
While interfaces are allowed to extend to other interfaces, sub
interfaces cannot define the methods declared in the super
interfaces.
After all, sub interfaces are still interfaces, not classes.
Instead, it is the responsibility of any class that implements the
derived interface to define all the methods.
Note that when an interface extends two or more interfaces,
they are separated by commas.
It is important to remember that an interface cannot extend
classes. This would violate the rule that an interface can have
only abstract methods and constants.

12
Implementing Interfaces
Interfaces are used as super classes whose properties are
inherited by classes.
It is therefore necessary to create a class that inherits the given
interface. This is done as follows:
class class_name implements interface_name
{
body of class_name
}

12
Implementing Interfaces
Here the class class_name implements the interface
interface_name.
A more general form of implementation may look like this:
class class_name extends super_class implements
interface-1, interface-2,…….interface-n
{
body of class_name
}

12
Cont.

This shows that a class can extend another class while implementing
interfaces.
When a class implements more than one interface, they are separated
by comma.
Now, consider the following program.

In this program, an interface Area is created. This interface is


implemented for two different classes, Rectangle and Circle. In the
main method, the instances of both the classes are created. After this,
the object of the interface Area is created and the reference to the
Rectangle object r is assigned to this object. When the compute
method of ‘a’ is called, the compute method of Rectangle is invoked.
The same thing is repeated for the Circle object.
Program
// This program illustrates the use of the interface, in multiple inheritance
interface Area // Interface Definition
{
final static double pi = 3.14 ;
double compute(double x, double y);
}
class Rectangle implements Area // Implementation of the interface
{
public double compute(double x, double y)
{
return (x*y);
}
}
class Circle implements Area // Implementation of the interface
{
public double compute(double x, double y)
{
return(pi*x*x);
}
}
class Interface_Example Cont.
{
public static void main(String args[])
{
Rectangle r = new Rectangle( );
Circle c = new Circle( );
Area a ; // Object of the Interface
a=r;
System.out.println("\n Area of Rectangle = " + a.compute(15.5, 12.3));
a=c;
System.out.println(" Area of Circle = " + a.compute(12.5, 0.0));
}
}

Output:
Area of Rectangle = 190.65
Area of Circle = 490.625
Accessing Interface Variables
Interfaces can be used to declare a set of constants that can be used in
different classes.

This is similar to creating header files in C++ to contain a large


number of constants.

Since such interfaces do not contain methods, there is no need to


worry about implementing any methods.

The constant values will be available to any class that implements the
interface.

The values can be used in any method, as part of any variable


declaration, or anywhere where one can use a final value.
Cont.
For example, consider the following segment:
interface A
{
int m = 10 ;
int n = 50 ;
}
class B implements A
{
int x = m ;
void methodB(int size)
{
………….
if (size < n)
………….
}
}
Hybrid Inheritance in Java

class Student

extends

class Test interface Sports

extends implements

class Results
Example
class Student // Super class
{
int roll_no ;
void getNumber(int n)
{ roll_no = n ; }
void putNumber( )
{ System.out.println("\n Roll no: = " + roll_no); }
} // End of the super class
class Test extends Student // Sub class
{
float part1, part2 ;
void getMarks(float m1, float m2)
{ part1 = m1 ; part2 = m2 ; }
void putMarks( )
{
System.out.println(" Marks obtained" );
System.out.println(" Part1 = " + part1);
System.out.println(" Part2 = " + part2);
}
}
interface Sports
{
float sportWt = 6.0f ;
void putWt( );
}
class Results extends Test implements Sports
{
float total ;
public void putWt( )
{
System.out.println(" Sports Wt = " + sportWt);
}
void display( )
{
total = part1 + part2 + sportWt ;
putNumber( );
putMarks( );
putWt( );
System.out.println(" Total score = " + total);
}
}
class Hybrid
{
public static void main(String args[ ])
{
Results student1 = new Results( );
student1.getNumber(1234);
student1.getMarks(27.5f, 24.5f);
student1.display( );
}
}

Output:
Roll no: = 1234
Marks obtained
Part1 = 27.5
Part2 = 24.5
Sports Wt = 6.0
Total Score = 58.0
Dynamic Binding, using an interface
interface Shape
{
float PI=3.14F;
void displayArea();
}
class Circle implements Shape
{
private float radius ;
public Circle(float r)
{ radius = r; }
public void displayArea()
{ System.out.print(“\n Area of the Circle is: “ + (PI *radius*radius) ) ; }
}
class Rectangle implements Shape
{
private float length, breadth;
public Rectangle(float l, float b)
{ Length =l; breadth = b; }
public void displayArea()
{ System.out.print(“\n Area of rectangle = “ + (length*breadth) ) ; }
}
class ShapeRun
{
public static void main(String args[])
{
Shape s ;
Circle c = new Circle(5.5f);
s=c;
s.displayArea();
Rectangle r = new Rectangle(5.5f 3.5f) ;
s=r;
s.displayArea();
}
}

Output:
Abstract Class Interface
Abstract classes are used only when Interfaces can be implemented by
there is a “is-a” type of relationship classes that are not related to one
between the classes. another.
You cannot extend more than one You can implement more than one
abstract class. interface.
Abstract class can implemented some Interfaces can not implement methods.
methods also.
With abstract classes, you are grabbing With Interfaces, you are merely
away each class’s individuality. extending each class’s functionality.
An abstract class can have instance An Interface can only declare constants
methods that implement a default and instance methods, but cannot
behavior. implement default behavior and all
methods are implicitly abstract.
An abstract class is a class which may An interface has all public members
have the usual flavors of class members and no implementation.
(private, protected, etc.), but has some
abstract methods.
When to use the interface and an abstract class?
Interfaces are useful when you do not want classes to inherit
from unrelated classes just to get the required functionality.

For example, let Bird be a class with a method fly(). It will


be ridiculous for an Aeroplane to inherit from Bird class
just because it has the fly() method.

Rather the fly() method should be defined as an interface


and both Bird and Aeroplane should implement that
interface.
When to use the interface and an abstract class? (An
example)

Consider a real estate builder is constructing an


apartment with many flats. All the rooms in the
flats have the same design, except the bedroom.
The bedroom design is left for the people who
would own the flats i.e. the bedrooms can be of
different designs for different flats.
The solution to above can be achieved through an abstract class like below:

public abstract class Flat


{
//some properties / variables

public void livingRoom()


{ //some code }
public void kitchen()
{ //some code }
public abstract void bedRoom( );
}
public class Flat101 extends Flat
{
public void bedRoom()
{
System.out.println("This flat has a customized bedroom");
}
}
Alternatively I can use an interface instead of an abstract class to achieve
the same purpose like follows:
class Flat
{
public void livingRoom()
{ System.out.println("This flat has a living room"); }
public void kitchen()
{ System.out.println("This flat has a kitchen"); }
}
interface BedRoomInterface
{
public abstract void bedRoom();
}
public class Flat101 extends Flat implements BedRoomInterface
{
public void bedRoom()
{
System.out.println("This flat has a customized
bedroom");
}
}
Now the question is: For this setup why should I choose to use an interface
(or) why should I choose to use an abstract class?

➢An interface would be best choice for above case. Because you got
the method which got various implementations. So it's the key concept
if your methods got various implementations you should always go for
interface.
➢This is because when you define an object of the class Flat101 you will have
access to all the method and can any time tamper the implementation.

➢On the other hand if you get the interface object, you can only invoke the
method but not modify. Security can be achieved through interfaces
Interface Nesting
public interface outerinter{
void display();
interface Inner {
void Innermethod();
}
}

14
class fibo implements outerinter.Inner {

public void Innermethod()


{
int n=10,t1=0,t2=1;
System.out.println("First "+n+" terms");
for(int i=1;i<=10; i++)
{
System.out.print(t1 + "+");
int sum=t1+t2;
t1=t2;
t2=sum;
}

14
System.out.println("Printing from nested interface method");
}
public static void main(String args[])
{
outerinter.Inner obj= new fibo();
obj.Innermethod();
}

14
THANK YOU

You might also like