0% found this document useful (0 votes)
2 views50 pages

JAVA Module3 Notes

This document covers the concept of inheritance in Java, explaining its importance in object-oriented programming, types of inheritance, and the use of the 'super' keyword. It details method overriding, its rules, and provides examples for single, multilevel, and hierarchical inheritance. The document emphasizes code reusability and runtime polymorphism as key benefits of inheritance.

Uploaded by

vishalkammar99
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)
2 views50 pages

JAVA Module3 Notes

This document covers the concept of inheritance in Java, explaining its importance in object-oriented programming, types of inheritance, and the use of the 'super' keyword. It details method overriding, its rules, and provides examples for single, multilevel, and hierarchical inheritance. The document emphasizes code reusability and runtime polymorphism as key benefits of inheritance.

Uploaded by

vishalkammar99
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

Object Oriented Programming with Java ****** 23CSO612

Object Oriented Programming with


JAVA
(23CSO612)

MODULE 3

Inheritance: Inheritance Basics, Using super, Creating a Multilevel Hierarchy, When

Constructors Are Executed, Method Overriding, Dynamic Method Dispatch, Using Abstract

Classes, Using final with Inheritance, Local Variable Type Inference and Inheritance, The Object

Class.

[Link], Dept. of CSE, SJBIT Page 1


Object Oriented Programming with Java ****** 23CSO612

Inheritance in Java

1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

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


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
o 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.
o 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.
o 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.

[Link], Dept. of CSE, SJBIT Page 2


Object Oriented Programming with Java ****** 23CSO612

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer
is a type of Employee.

[Link], Dept. of CSE, SJBIT Page 3


Object Oriented Programming with Java ****** 23CSO612

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee
class i.e. code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.

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

[Link], Dept. of CSE, SJBIT Page 4


Object Oriented Programming with Java ****** 23CSO612

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

[Link], Dept. of CSE, SJBIT Page 5


Object Oriented Programming with Java ****** 23CSO612

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below,
Dog class inherits the Animal class, so there is the single inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class,
so there is a multilevel inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}

[Link], Dept. of CSE, SJBIT Page 6


Object Oriented Programming with Java ****** 23CSO612

}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();

[Link], Dept. of CSE, SJBIT Page 7


Object Oriented Programming with Java ****** 23CSO612

[Link]();
[Link]();
//[Link]();//[Link]
}}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, 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 the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

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.

class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


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

Super Keyword in Java


[Link], Dept. of CSE, SJBIT Page 8
Object Oriented Programming with Java ****** 23CSO612

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.

1) super is used to refer immediate parent class instance variable.


We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.

class Animal{
String color="white";
[Link], Dept. of CSE, SJBIT Page 9
Object Oriented Programming with Java ****** 23CSO612

}
class Dog extends Animal{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property, we
need to use super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void eat(){[Link]("eating bread...");}
void bark(){[Link]("barking...");}
void work(){
[Link]();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}

[Link], Dept. of CSE, SJBIT Page 10


Object Oriented Programming with Java ****** 23CSO612

Output:

eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from
Dog class, it will call the eat() method of Dog class by default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:

class Animal{
Animal(){[Link]("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
[Link]("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

[Link], Dept. of CSE, SJBIT Page 11


Object Oriented Programming with Java ****** 23CSO612

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

As we know well that default constructor is provided by compiler automatically if there is no


constructor. But, it also adds super() as the first statement.

Another example of super keyword where super() is provided by the compiler implicitly.

class Animal{
Animal(){[Link]("animal is created");}
}
class Dog extends Animal{
Dog(){
[Link]("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created
super example: real use
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties
of Person will be inherited to Emp by default. To initialize all the property, we are using parent
class constructor from child class. In such way, we are reusing the parent class constructor.

class Person{

[Link], Dept. of CSE, SJBIT Page 12


Object Oriented Programming with Java ****** 23CSO612

int id;
String name;
Person(int id,String name){
[Link]=id;
[Link]=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
[Link]=salary;
}
void display(){[Link](id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
[Link]();
}}

Output:

1 ankit 45000

[Link], Dept. of CSE, SJBIT Page 13


Object Oriented Programming with Java ****** 23CSO612

Method Overriding

If subclass (child class) has the same method as declared in the parent class, it is known as method

overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been

declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

1. Method overriding is used to provide the specific implementation of a method that is

already provided by its superclass.

2. Method overriding is used for runtime polymorphism.

3. Method overriding allows subclasses to reuse and build upon the functionality provided by

their superclass, reducing redundancy and promoting modular code design.

4. Subclasses can override methods to tailor them to their specific needs or to implement

specialized behavior that is unique to the subclass.

5. Method overriding enables dynamic method dispatch, where the actual method

implementation to be executed is determined at runtime based on the type of object,

supporting flexibility and polymorphic behavior.

Rules for Java Method Overriding

1. Same Method Name: The overriding method in the subclass must have the same name as

the method in the superclass that it is overriding.

[Link], Dept. of CSE, SJBIT Page 14


Object Oriented Programming with Java ****** 23CSO612

2. Same Parameters: The overriding method must have the same number and types of

parameters as the method in the superclass. This ensures compatibility and consistency

with the method signature defined in the superclass.

3. IS-A Relationship (Inheritance): Method overriding requires an IS-A relationship

between the subclass and the superclass. This means that the subclass must inherit from

the superclass, either directly or indirectly, to override its methods.

4. Same Return Type or Covariant Return Type: The return type of the overriding method

can be the same as the return type of the overridden method in the superclass, or it can be

a subtype of the return type in the superclass. This is known as the covariant return type,

introduced in Java 5.

5. Access Modifier Restrictions: The access modifier of the overriding method must be the

same as or less restrictive than the access modifier of the overridden method in the

superclass. Specifically, a method declared as public in the superclass can be overridden

as public or protected but not as private. Similarly, a method declared as protected in the

superclass can be overridden as protected or public but not as private. A method declared

as default (package-private) in the superclass can be overridden with default, protected, or

public, but not as private.

6. No Final Methods: Methods declared as final in the superclass cannot be overridden in

the subclass. This is because final methods cannot be modified or extended.

7. No Static Methods: Static methods in Java are resolved at compile time and cannot be

overridden. Instead, they are hidden in the subclass if a method with the same signature is

defined in the subclass.

[Link], Dept. of CSE, SJBIT Page 15


Object Oriented Programming with Java ****** 23CSO612

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

[Link]

//Java Program to demonstrate why we need method overriding

//Here, we are calling the method of parent class with child

//class object.

//Creating a parent class

class Vehicle{

void run(){[Link]("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

[Link]();

Output:

Vehicle is running

Explanation

[Link], Dept. of CSE, SJBIT Page 16


Object Oriented Programming with Java ****** 23CSO612

"Vehicle is running" is printed by the run() function of the Vehicle class. We construct an instance

of the Bike class and use it to invoke the run() method within the Bike class. As a result of Bike

deriving from Vehicle, the run() function of the Vehicle class is overridden in the Bike class,

resulting in the print "Vehicle is running" when the method is used on a Bike object. This

demonstrates how method overriding, in which the method specified in the subclass overrides the

method in the superclass with the identical signature, can result in polymorphic behaviour.

Example of Method Overriding

In this example, we have defined the run method in the subclass as defined in the parent class, but

it has some specific implementation. The method's name and parameters are the same, and there

is an IS-A relationship between the classes, so there is method overriding.

[Link]

//Java Program to illustrate the use of Java Method Overriding

//Creating a parent class.

class Vehicle{

//defining a method

void run(){[Link]("Vehicle is running");}

//Creating a child class

class Bike2 extends Vehicle{

//defining the same method as in the parent class

void run(){[Link]("Bike is running safely");}

public static void main(String args[]){

[Link], Dept. of CSE, SJBIT Page 17


Object Oriented Programming with Java ****** 23CSO612

Bike2 obj = new Bike2();//creating object

[Link]();//calling method

Output:

Bike is running safely

Explanation

A method in a subclass (Bike2) overrides the same method in its superclass (Vehicle), as this Java

program illustrates. The run() method in this example is shared by both types, but the Bike2 class

implements it differently, outputting "Bike is running safely." The overridden function in the Bike2

class gets executed when we create an instance of Bike2 and use the run() method on it, proving

that the implementation of the subclass takes precedence over the implementation of the

superclass. This demonstrates how Java's dynamic polymorphism feature allows methods with the

same signature to behave differently in various classes, even if they are part of the same inheritance

tree.

A real example of Java Method Overriding

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.

[Link]

//Java Program to demonstrate the real scenario of Java Method Overriding

[Link], Dept. of CSE, SJBIT Page 18


Object Oriented Programming with Java ****** 23CSO612

//where three classes are overriding the method of a parent class.

//Creating a parent class.

class Bank{

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;}

//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();

[Link]("SBI Rate of Interest: "+[Link]());

[Link], Dept. of CSE, SJBIT Page 19


Object Oriented Programming with Java ****** 23CSO612

[Link]("ICICI Rate of Interest: "+[Link]());

[Link]("AXIS Rate of Interest: "+[Link]());

Output:

SBI Rate of Interest: 8

ICICI Rate of Interest: 7

AXIS Rate of Interest: 9

Explanation

This Java programme uses a real-world scenario where three classes-SBI, ICICI, and AXIS-

override a method from their parent class, Bank, to demonstrate the idea of method overriding.

The getRateOfInterest() function of the Bank class yields 0. With their own implementation, each

of the child classes overrides this method: SBI returns 8, ICICI returns 7, and AXIS returns 9. Each

child class object is created in the Test2 class, and then each object's getRateOfInterest() method

is used to print out the corresponding interest rates for each bank. This illustrates how polymorphic

behaviour dependent on the type of object at runtime is made possible by method overriding, which

enables each subclass to give its own implementation of a method inherited from the superclass.

Can we override the static method?

No, a static method cannot be overridden in Java. When a subclass defines a static method with

the same signature as a static method in its superclass, it is simply hiding the superclass method,

not overriding it. This means that the method invoked is determined at compile time based on the

[Link], Dept. of CSE, SJBIT Page 20


Object Oriented Programming with Java ****** 23CSO612

reference type, not at runtime based on the object's type. Therefore, static methods do not exhibit

polymorphic behavior like instance methods do.

Why can we not override static method?

Because static methods in Java are linked to the class itself rather than any specific instance of the

class, we are unable to override them. Java's dynamic dispatch mechanism, which determines the

method to be called at runtime depending on the object's actual type, forms the foundation for

method overriding.

Static methods cannot be overridden in the same manner as instance methods since they are not

subject to dynamic dispatch because they are resolved at compile time based on the reference type

and are part of the class.

Furthermore, while instance methods are kept in the object's heap area and are specific to each

instance of the class, static methods are kept in the method region of the JVM's memory, which is

shared by all instances of the class. Static methods cannot be altered due to the basic differences

in their behaviour and memory allocation between instance and static methods.

Can we override Java main() method?

No, because the Java main() method is designated as static, we are unable to override it. The main

function in Java is declared as public static void main(String[] args) and acts as the program's

starting point.

The method in question is part of the class itself, not any particular instance of the class, as

indicated by the use of the static keyword.

[Link], Dept. of CSE, SJBIT Page 21


Object Oriented Programming with Java ****** 23CSO612

It is not possible to override the main method in a subclass since static methods are not overridable.

As the initial point of execution, each Java program must contain exactly one main method that

has the required signature.

Method Overloading Vs. Method Overriding

Aspect Method overloading Method overriding

Method overriding is used to

Method overloading is used to provide the specific

Purpose and Intent increase the readability of the implementation of the method

program. that is already provided by its

superclass.

Method overriding occurs in two


Method overloading is
Relationship between Classes classes that have IS-A
performed within class.
(inheritance) relationship.

In case of method overloading, In case of method overriding,


Parameter Requirements
parameters must be different. parameters must be the same.

Method overloading is the Method overriding is the

Polymorphism Type example of compile-time example of runtime

polymorphism. polymorphism.

[Link], Dept. of CSE, SJBIT Page 22


Object Oriented Programming with Java ****** 23CSO612

In Java, method overloading

can't be performed by changing

the return type of the method


Return type must be the same or
Return Type Constraints only. Return type can be the
covariant in method overriding.
same or different in method

overloading, but you must have

to change the parameter.

Java Access Modifiers with Method Overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more

restrictive.

[Link]

class A{

protected void msg(){[Link]("Hello java");}

public class Simple extends A{

void msg(){[Link]("Hello java");}//[Link]

public static void main(String args[]){

Simple obj=new Simple();

[Link]();

[Link], Dept. of CSE, SJBIT Page 23


Object Oriented Programming with Java ****** 23CSO612

Output:

Compile time error

Explanation

Class A declares a method called msg() with the protected access modifier in the provided Java

code. By extending class A, class Simple aims to replace the message() function with a default

access modifier. But because the default access modifier is more restricted than protected, this

leads to a compile-time error. When overriding a method in Java, the overridden method's access

level in the subclass needs to be at least as liberal as the method's access level in the superclass.

Thus, in order to fix the issue, either the class Simple method's access modifier-such as protected

or public-should be as liberal as protected, or the class A method should have a less permissive

access modifier-such as default or public.

Dynamic Method Dispatch Java

Java, as an object-oriented programming language, supports one of the key features of OOP -

polymorphism. It allows objects to take on multiple forms, and one way it achieves this is through

a mechanism called dynamic method dispatch. The feature plays a crucial role in achieving

flexibility and extensibility in Java programs.

Polymorphism

Before delving into dynamic method dispatch, it is important to grasp the concept of

polymorphism. In Java, polymorphism allows objects to be treated as instances of their superclass,

enabling code to work with objects of different types in a uniform way.

[Link], Dept. of CSE, SJBIT Page 24


Object Oriented Programming with Java ****** 23CSO612

For example, if we have a superclass Animal and subclasses Dog and Cat, we can create an array

of Animal objects and store instances of both Dog and Cat in it. We can then iterate through the

array and call a method like makeSound() on each element, and the appropriate version of

makeSound() from either Dog or Cat will be executed.

class Animal {

void makeSound() {

[Link]("Generic Animal Sound");

class Dog extends Animal {

@Override

void makeSound() {

[Link]("Bark");

class Cat extends Animal {

@Override

void makeSound() {

[Link]("Meow");

public class Demo {

public static void main(String[] args) {

[Link], Dept. of CSE, SJBIT Page 25


Object Oriented Programming with Java ****** 23CSO612

Animal[] animals = {new Dog(), new Cat()};

for (Animal animal : animals) {

[Link]();

In this example, we have created an array of Animal objects and populate it with instances of Dog

and Cat. When we call makeSound() on each element, the version defined in the subclass will be

executed due to dynamic method dispatch.

Dynamic Method Dispatch

Dynamic method dispatch or run-time polymorphism is the mechanism through which the correct

version of an overridden method is called at runtime. When a subclass overrides a method from its

superclass, the overridden method in the subclass is executed when called on an instance of the

subclass, even if the reference to the object is of the superclass type.

In the previous example, when we call [Link]() in the loop, the appropriate

makeSound() method defined in either Dog or Cat is executed based on the actual type of the

object.

It is a powerful feature because it allows for flexibility in the way we write code. We can write

methods in the superclass that are common to all subclasses, and then have specific behavior

defined in each subclass.

[Link], Dept. of CSE, SJBIT Page 26


Object Oriented Programming with Java ****** 23CSO612

Use Cases for Dynamic Method Dispatch

Dynamic method dispatch is particularly useful in scenarios where we want to write code that

operates on a general type but can be specialized by subclasses. It promotes code reusability and

allows for cleaner and more modular code.

For example, if we were building a game with different types of characters (for example, warriors,

mages, archers), we could have a Character superclass with the attack() method. Each specific

character type (warrior, mage, archer) would then override the attack() method with its own

implementation. It allows us to write code that can handle any type of character without knowing

the specific details of how each one attacks.

Complete Java program that demonstrates dynamic method dispatch along with input and output.

[Link]

class Animal {

void makeSound() {

[Link]("Generic Animal Sound");

class Dog extends Animal {

@Override

void makeSound() {

[Link]("Bark");

[Link], Dept. of CSE, SJBIT Page 27


Object Oriented Programming with Java ****** 23CSO612

class Cat extends Animal {

@Override

void makeSound() {

[Link]("Meow");

public class DynamicMethod {

public static void main(String[] args) {

Animal[] animals = {new Dog(), new Cat()};

for (Animal animal : animals) {

[Link]();

Output:

Bark

Meow

In the Main class, we have created an array of Animal objects called animals and populate it with

an instance of Dog and an instance of Cat. We then iterate through the animals array using a for-

each loop and call the makeSound() method on each element. Due to dynamic method dispatch,

the appropriate version of makeSound() from either Dog or Cat will be executed based on the

actual type of the object.

[Link], Dept. of CSE, SJBIT Page 28


Object Oriented Programming with Java ****** 23CSO612

Dynamic method dispatch is a powerful feature of Java that enables polymorphism and promotes

code reusability and modularity. By allowing objects to take on multiple forms, Java provides a

flexible and extensible platform for building complex applications.

Understanding dynamic method dispatch is essential for writing efficient and maintainable code

in Java, especially in scenarios where you want to work with objects at a higher level of abstraction.

It is a fundamental concept in object-oriented programming that every Java developer should

master.

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal
processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

[Link], Dept. of CSE, SJBIT Page 29


Object Oriented Programming with Java ****** 23CSO612

Points to Remember

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Example of abstract class

1. abstract class A{}

[Link], Dept. of CSE, SJBIT Page 30


Object Oriented Programming with Java ****** 23CSO612

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract
method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){[Link]("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
[Link]();
}
}
Test it Now
running safely

Understanding the real scenario of Abstract class

In this example, Shape is the abstract class, and its implementation is provided by the Rectangle
and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an
object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the factory
method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.

File: [Link]

[Link], Dept. of CSE, SJBIT Page 31


Object Oriented Programming with Java ****** 23CSO612

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(){[Link]("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){[Link]("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
[Link]();
}
}
Test it Now
drawing circle

Another example of Abstract class in java

File: [Link]

abstract class Bank{


abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

[Link], Dept. of CSE, SJBIT Page 32


Object Oriented Programming with Java ****** 23CSO612

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
[Link]("Rate of Interest is: "+[Link]()+" %");
b=new PNB();
[Link]("Rate of Interest is: "+[Link]()+" %");
}}
Test it Now
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Abstract class having constructor, data member and methods

An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.

File: [Link]

//Example of an abstract class that has abstract and non-abstract methods


abstract class Bike{
Bike(){[Link]("bike is created");}
abstract void run();
void changeGear(){[Link]("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){[Link]("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
[Link]();
[Link]();
}
}
[Link], Dept. of CSE, SJBIT Page 33
Object Oriented Programming with Java ****** 23CSO612

Test it Now
bike is created
running safely..
gear changed

Rule: If there is an abstract method in a class, that class must be abstract.

class Bike12{
abstract void run();
}
Test it Now
compile time error

Rule: If you are extending an abstract class that has an abstract method, you must either provide
the implementation of the method or make this class abstract.

Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In such case,
the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.

1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){[Link]("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){[Link]("I am a");}
14. public void b(){[Link]("I am b");}
15. public void d(){[Link]("I am d");}

[Link], Dept. of CSE, SJBIT Page 34


Object Oriented Programming with Java ****** 23CSO612

16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Test it Now
Output:I am a
I am b
I am c
I am d

Local Variable Type Inference or LVTI in Java 10


What is type inference?

Type inference refers to the automatic detection of the datatype of a variable, done generally at

the compiler time.

What is Local Variable type inference?

Local variable type inference is a feature in Java 10 that allows the developer to skip the type

declaration associated with local variables (those defined inside method definitions, initialization

blocks, for-loops, and other blocks like if-else), and the type is inferred by the JDK. It will, then,

be the job of the compiler to figure out the datatype of the variable.

Why has this feature been introduced?

Till Java 9, to define a local variables of class type, the following was the only correct syntax:

Class_name variable_name=new Class_name(arguments);

[Link], Dept. of CSE, SJBIT Page 35


Object Oriented Programming with Java ****** 23CSO612

For example:

// Sample Java local variable declaration

import [Link];

import [Link];

class A {

public static void main(String a[])

List<Map> data = new ArrayList<>();

Or

class A {

public static void main(String a[])

String s = " Hi there";

It looks fine, right? Yeah, because this is how things have been since the inception of Java. But
there is one issue: It’s pretty obvious that if the type of the object is clearly mentioned at the
right side of the expression, mentioning the same thing before the name of the variable makes
it redundant. Plus, in the second example, you can see that it’s obvious that after the ‘=’ sign,
it’s clearly a string as nothing except for a string can be enclosed in double inverted commas.

[Link], Dept. of CSE, SJBIT Page 36


Object Oriented Programming with Java ****** 23CSO612

Therefore, there arose a need to eliminate this redundancy and make variable declaration
shorter, and more convenient.
How to declare local variables using LVTI:
Instead of mentioning the variable datatype on the left-side, before the variable, LVTI allows
you to simply put the keyword ‘var’. For example,

// Java code for Normal local

// variable declaration

import [Link];

import [Link];

class A {

public static void main(String ap[])

List<Map> data = new ArrayList<>();

Can be re-written as:

// Java code for local variable

// declaration using LVTI

import [Link];

import [Link];

class A {

public static void main(String ap[])

[Link], Dept. of CSE, SJBIT Page 37


Object Oriented Programming with Java ****** 23CSO612

var data = new ArrayList<>();

Use Cases
Here are the cases where you can declare variables using LVTI:
1. In a static/instance initialization block

// Declaration of variables in static/init

// block using LVTI in Java 10

class A {

static

var x = "Hi there";

[Link](x)'

public static void main(String[] ax)

Output:
Oh hi there
2. As a local variable

[Link], Dept. of CSE, SJBIT Page 38


Object Oriented Programming with Java ****** 23CSO612

// Declaration of a local variable in java 10 using LVTI

class A {

public static void main(String a[])

var x = "Hi there";

[Link](x)

Output:
Hi there
3. As iteration variable in enhanced for-loop

// Declaring iteration variables in enhanced for loops using LVTI in Java

class A {

public static void main(String a[])

int[] arr = new int[3];

arr = { 1, 2, 3 };

for (var x : arr)

[Link](x + "\n");

[Link], Dept. of CSE, SJBIT Page 39


Object Oriented Programming with Java ****** 23CSO612

Output:
1
2
3
4. As looping index in for-loop

// Declaring index variables in for loops using LVTI in Java

class A {

public static void main(String a[])

int[] arr = new int[3];

arr = { 1, 2, 3 };

for (var x = 0; x < 3; x++)

[Link](arr[x] + "\n");

Output:
1
2
3
5. As a return value from another method

// Storing the return value of a function in a variable declared with LVTI

[Link], Dept. of CSE, SJBIT Page 40


Object Oriented Programming with Java ****** 23CSO612

class A {

int ret()

return 1;

public static void main(String a[])

var x = new A().ret();

[Link](x);

Output:
1
6. As a return value in a method

// Using a variable declared

//using the keyword 'var' as a return value of a function

class A {

int ret()

var x = 1;

return x;

[Link], Dept. of CSE, SJBIT Page 41


Object Oriented Programming with Java ****** 23CSO612

public static void main(String a[])

[Link](new A().ret());

Output:
1
Error cases:
There are cases where declaration of local variables using the keyword ‘var’ produces an error.
They’re mentioned below:
1. Not permitted in class fields

// Sample java code to demonstrate

//that declaring class variables

//using 'var' is not permitted

class A {

var x; /* Error: class variables can't be declared

using 'var'. Datatype needs

to be explicitly mentioned*/

2. Not permitted for uninitialized local variables

// Sample java code to demonstrate

//that declaring uninitialized

[Link], Dept. of CSE, SJBIT Page 42


Object Oriented Programming with Java ****** 23CSO612

//local variables using 'var' produces an error

class A {

public static void main(String a[])

var x; /* error: cannot use 'var'

on variable without initializer*/

3. Not allowed as parameter for any methods

// Java code to demonstrate that

// var can't be used in case of

//any method parameters

class A {

void show(var a) /*Error: can't use 'var'

on method parameters*/

4. Not permitted in method return type

[Link], Dept. of CSE, SJBIT Page 43


Object Oriented Programming with Java ****** 23CSO612

// Java code to demonstrate

// that a method return type

// can't be 'var'

class A {

public var show() /* Error: Method return type

can't be var*/

return 1;

5. Not permitted with variable initialized with ‘NULL’

// Java code to demonstrate that local

variables initialized with 'Null'

can't be declared using 'var'*/

class A {

public static void main(String a[])

var x = NULL; // Error: variable initializer is 'null'

Note: All these pieces of code run only on Java 10.

[Link], Dept. of CSE, SJBIT Page 44


Object Oriented Programming with Java ****** 23CSO612

Object class in Java

The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Methods of Object class

The Object class provides many methods. They are as follows:

Methods Description

returns the Class class object of this


object. The Class class can further
public final Class getClass()
be used to get the metadata of this
class.

[Link], Dept. of CSE, SJBIT Page 45


Object Oriented Programming with Java ****** 23CSO612

returns the hashcode number for


public int hashCode()
this object.

compares the given object to this


public boolean equals(Object obj)
object.

creates and returns the exact copy


protected Object clone() throws CloneNotSupportedException
(clone) of this object.

returns the string representation of


public String toString()
this object.

wakes up single thread, waiting on


public final void notify()
this object's monitor.

wakes up all the threads, waiting on


public final void notifyAll()
this object's monitor.

causes the current thread to wait for


the specified milliseconds, until
public final void wait(long timeout)throws InterruptedException
another thread notifies (invokes
notify() or notifyAll() method).

causes the current thread to wait for


the specified milliseconds and
public final void wait(long timeout,int nanos)throws
nanoseconds, until another thread
InterruptedException
notifies (invokes notify() or
notifyAll() method).

causes the current thread to wait,


until another thread notifies
public final void wait()throws InterruptedException
(invokes notify() or notifyAll()
method).

[Link], Dept. of CSE, SJBIT Page 46


Object Oriented Programming with Java ****** 23CSO612

is invoked by the garbage collector


protected void finalize()throws Throwable before object is being garbage
collected.

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:

1. variable
2. method
3. 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. We will
have detailed learning of these. Let's first learn the basics of final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.

class Bike9{

[Link], Dept. of CSE, SJBIT Page 47


Object Oriented Programming with Java ****** 23CSO612

final int speedlimit=90;//final variable


void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}//end of class
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.

Example of final method


class Bike{
final void run(){[Link]("running");}
}

class Honda extends Bike{


void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
[Link]();
}
}
Output:Compile Time Error
3) Java final class
If you make any class as final, you cannot extend it.

Example of final class


final class Bike{}

class Honda1 extends Bike{


void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
[Link]();
}
}
Output:Compile Time Error

[Link], Dept. of CSE, SJBIT Page 48


Object Oriented Programming with Java ****** 23CSO612

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:

class Bike{
final void run(){[Link]("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized
may not be changed, it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable


class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
Q) Can we initialize blank final variable?
Yes, but only in constructor. For example:

class Bike10{
final int speedlimit;//blank final variable

Bike10(){
speedlimit=70;
[Link](speedlimit);
}

public static void main(String args[]){


new Bike10();
}
}
Output: 70

[Link], Dept. of CSE, SJBIT Page 49


Object Oriented Programming with Java ****** 23CSO612

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.

Example of static blank final variable


class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
[Link]([Link]);
}
}
Q) What is 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();
[Link](5);
}
}
Output: Compile Time Error
Q) Can we declare a constructor final?
No, because constructor is never inherited.

[Link], Dept. of CSE, SJBIT Page 50

You might also like