You are on page 1of 14

Method Overriding in Java

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

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method which is


already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

• Both the superclass and the subclass must have the same method name, the same return
type and the same parameter list.

• We cannot override the method declared as final and static.


• We should always override abstract methods of the superclass

Example 1: Method Overriding

class Animal
{
public void display()
{
System.out.println("I am an animal.");
}
}

class Dog extends Animal


{
@Override
public void display()
{
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.display();
}
}
1 RESMI K R JAVA 3 BCA B
Output:

I am a dog.

Example 2: Use of super Keyword

class Animal {
public void display() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


public void display() {
super.display();
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.display();
}
}

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an


overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.
For example:

2 RESMI K R JAVA 3 BCA B


Java Runtime Polymorphism Example: Bank

Consider a scenario where Bank is a class that provides a method to get the rate of interest.
However, the rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS
banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

class Bank
{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank
{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank
{
float getRateOfInterest(){return 7.3f;}

3 RESMI K R JAVA 3 BCA B


}
class AXIS extends Bank
{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Final Keyword in JAVA


The final keyword is used in different contexts. Final keyword is used to restrict the users. The
final is a non-access modifier applicable only to a variable, a method, or a class. Following are
the different context of using the final keyword:

4 RESMI K R JAVA 3 BCA B


The final keyword in java is used to restrict the user. In Java, the final keyword can be used while
declaring an entity. Using the final keyword means that the value can’t be modified in the future.
Final can be:
• Variables
• Methods
• Classes
Final Variables in Java
When a variable is declared with the final keyword, its value can’t be modified, essentially, a
constant. This also means that you must initialize a final variable. The final variable cannot be
reinitialized with another value.
Note :
• The variable does not necessarily have to be initialized at the time of declaration.
If it’s declared but not yet initialized, it’s called a blank final variable. This
approach is the most common.
• It is recommended to use uppercase to declare final variables in Java.
How to initialize a blank final variable?
Below are the two ways to initialize a blank final variable:
1. A blank final variable can be initialized inside the instance-initializer block or
inside the constructor. If you have more than one constructor in your class then it
must be initialized in all of them, otherwise, a compile-time error will be thrown.
2. A blank final static variable can be initialized inside a static block.

Sample Program to demonstrate the final variable in Java:


public class FinalVariableDemo
{
final int speedlimit = 90; //final variable
void run ()
{
speedlimit = 400;
}
public static void main (String args[])
5 RESMI K R JAVA 3 BCA B
{
FinalVariableDemo obj = new FinalVariableDemo ();
obj.run ();
}
}
Output: Compile-Time Error
There is a final variable speed limit, we are going to change the value of this variable, but it can’t
be changed because the final variable once assigned a value can never be changed.

Final Methods in Java


A final method cannot be overridden or hidden by subclasses which means even though a subclass
can call the final method of parent class without any issues but it cannot override it. This is used
to prevent unexpected behavior from a subclass altering a method that may be crucial to the
function or consistency of the class. The main intention of making a method final would be that
the content of the method should not be changed by any outsider.
Example demonstrating Final Methods in Java:
class Bike
{
final void run()
{
System.out.println ("running");
}
}
class Honda extends Bike
{
void run()
{
// COMPILE-ERROR! Can't override.
System.out.println ("running safely with 100kmph");
}
public static void main (String args[])
{
Honda honda = new Honda ();
honda.run();
}
}
Output: Compile-Time Error
In the above example, we have tried to override the final method in the main() class. When we
run the program, we will get a compilation error.
Final Class in Java
6 RESMI K R JAVA 3 BCA B
In Java, the final class cannot be inherited by another class. The main purpose of using a class
being declared as final is to prevent the class from being subclasses. If a class is marked as final
then no class can inherit any feature from the final class.
Example to demonstrate Final Class in Class:
final class FinalClass
{
// create a final method
public void display ()
{
System.out.println ("This is a final method.");
}
}
class Main extends FinalClass
{
// try to override final method
public void display ()
{
System.out.println ("The final method is overridden.");
}
public static void main (String[]args)
{
Main obj = new Main ();
obj.display ();
}
}
Output: Compile-time Error
In the above example, we have created a final class named Final class. Here, we have tried to
inherit the final class from the Main class. When we run the program, we will get a compilation
error

1) Is final method inherited?

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

class Bike
{
final void run()
{
System.out.println("running...");}
7 RESMI K R JAVA 3 BCA B
}
class Honda extends Bike
{
public static void main (String args[])
{
new Honda().run();
}
}

Output:running...

) 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;
...
}
Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

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

Bike(){
speedlimit=70;
System.out.println(speedlimit);
}
8 RESMI K R JAVA 3 BCA B
public static void main(String args[]){
Bike obj=new Bike();
Or
new Bike();
}
}

Output: 70

static blank final variable

A static final variable that is not initialized at the time of declaration is known as staticblank
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[]){
System.out.println(A.data);
}

}
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();
9 RESMI K R JAVA 3 BCA B
b.cube(5);
}
}

Output: Compile Time Error


Q) Can we declare a constructor final?

No, because constructor is never inherited.

Note:
• The final method can be inherited but you cannot override it.
• The blank Final Variable can be initialized only in the constructor.
• Constructors cannot be declared as final because they cannot be inherited.

Abstract class in Java


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

Abstraction in Java

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


functionality to the user.

Abstraction lets you focus on what the object does instead of how it does it.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 canhave abstract


and non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.

Points to Remember

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


10 RESMI K R JAVA 3 BCA B
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 thebody of the
method.

Example of abstract class

abstract class A{}

Abstract Method in Java

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

Example of abstract method

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 Honda extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[])

Bike obj = new Honda();

obj.run();

}
}

11 RESMI K R JAVA 3 BCA B


OUTPUT

running safely

abstract class Shape


{
abstract void draw();
}
class Rectangle extends Shape
{
void draw(){System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}
class TestAbstraction{
public static void main(String args[])
{
Shape s=new Circle;
s.draw();
}
}

OUTPUT

drawing circle

12 RESMI K R JAVA 3 BCA B


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.

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

abstract class Bike {


Bike ()
{
System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}

//Creating a Child class which inherits Abstract class


class Honda extends Bike {
void run ()
{
System.out.println ("running safely..");
}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run(); obj.changeGear();
}
}
bike is created
running safely. gear
changed.

13 RESMI K R JAVA 3 BCA B


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

class Bike12
{
abstract void run ();
}

compile time error

Rule2: 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.

If you're making a new instruction booklet (a class) based on an existing


one (an abstract class) that has a blank space (an abstract method), you
must either fill in the blank space (implement the method) or leave your
booklet as a draft (make your class abstract)."

14 RESMI K R JAVA 3 BCA B

You might also like