Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Unit-III Methods and Inheritance in Java

Hhai

Uploaded by

aasavariwani03
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Unit-III Methods and Inheritance in Java

Hhai

Uploaded by

aasavariwani03
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Unit-III Methods and

Inheritance in Java
Mr. Shrikrishna Ulhas Kolhar
Abstraction in Java
• In object oriented programming, abstraction is defined as hiding the
unnecessary details (implementation) from the user and to focus on
essential details (functionality).

• It increases the efficiency and thus reduces complexity.

• In Java, abstraction can be achieved using abstract classes and


methods. In this tutorial, we will learn about abstract methods and its
use in Java.
Abstract class
A class is declared abstract using the abstract keyword. It can have zero or more abstract and
non-abstract methods. We need to extend the abstract class and implement its methods. It
cannot be instantiated.

Syntax for abstract class:


abstract class class_name {
//abstract or non-abstract methods
} Note: An abstract class may or may not contain abstract
methods.
Abstract Method
• A method declared using the abstract keyword within an abstract
class and does not have a definition (implementation) is called an
abstract method.
• When we need just the method declaration in a super class, it can be
achieved by declaring the methods as abstracts.
• Abstract method is also called subclass responsibility as it doesn't have
the implementation in the super class. Therefore a subclass must
override it to provide the method definition.

Syntax for abstract method:


abstract return_type method_name( [ argument-list ] );

• Here, the abstract method doesn't have a method body. It may have
zero or more arguments.
Example of Abstract Method in Java
Example 1:In the following example, we will learn how abstraction is achieved using abstract
classes and abstract methods. // Regular class extends abstract class
AbstractMethodEx1.java
class AbstractMethodEx1 extends Multiply {
// abstract class
// if the abstract methods are not implemented, compiler will
abstract class Multiply {
give an error
// abstract methods
public int MultiplyTwo (int num1, int num2) {
// sub class must implement these
return num1 * num2;
methods
}
public abstract int MultiplyTwo (i
public int MultiplyThree (int num1, int num2, int num3) {
nt n1, int n2);
return num1 * num2 * num3;
public abstract int MultiplyThree
}
(int n1, int n2, int n3);
// main method
// regular method with body
public static void main (String args[]) {
public void show() {
Multiply obj = new AbstractMethodEx1();
System.out.println ("Method of ab
System.out.println ("Multiplication of 2 numbers: " + obj.Mul
stract class Multiply");
tiplyTwo (10, 50));
}
System.out.println ("Multiplication of 3 numbers: " + obj.Mul
}
tiplyThree (5, 8, 10));
obj.show();
}
}
Points to Remember
Following points are the important rules for abstract method in Java:
• An abstract method do not have a body (implementation), they just
have a method signature (declaration). The class which extends the
abstract class implements the abstract methods.
• If a non-abstract (concrete) class extends an abstract class, then the
class must implement all the abstract methods of that abstract class. If
not the concrete class has to be declared as abstract as well.
• As the abstract methods just have the signature, it needs to have
semicolon (;) at the end.
• Following are various illegal combinations of other modifiers for
methods with respect to abstract modifier:
• final
• abstract native
• abstract synchronized
• abstract static
• abstract private
• abstract strictfp
Example 2:
By default, all the methods of an interface are public and abstract. An interface cannot contain
concrete methods i.e. regular methods with body.public class AbstractMethodEx2 implements Squ
AbstractMethodEx2.java areCube {
// interface
interface SquareCube { // defining the abstract methods of interface
// abstract methods public int squareNum (int num) {
public abstract int squareNum (int n); return num * num;
// it not necessary to add public and abstrac }
t keywords public int cubeNum (int num) {
// as the methods in interface are public ab return num * num * num;
stract by default }
int cubeNum (int n);
// regular methods are not allowed in a // main method
n interface public static void main(String args[]){
// if we uncomment this method, compi SquareCube obj = new AbstractMethodEx2();
ler will give an error System.out.println("Square of number is: " + o
/*public void disp() { bj.squareNum (7) );
System.out.println ("I will give erro System.out.println("Cube of number is: " + obj.
r if u uncomment me"); cubeNum (7));
} }
*/ }
}
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.

Example of abstract class


abstract class A{}

Points to Remember
• An abstract class must be declared with an abstract
keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
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(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

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

• In this example, if you create the instance of Rectangle class,


draw() method of Rectangle class will be invoked.
abstract class Shape{
abstract void draw();
}
//
In real scenario, implementation is provided b
y others i.e. unknown by end user
class Rectangle extends Shape{
void draw()
{System.out.println("drawing rectangle");}
} Output:
class Circle1 extends Shape{ drawing circle
void draw()
{System.out.println("drawing circle");}
}
//
In real scenario, method is called by program
mer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//
In a real scenario, object is provided through
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
} Output:
Rate of Interest is: 7 %
class TestBank{ Rate of Interest is: 8 %
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.ge
tRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.ge
tRateOfInterest()+" %");
}}
Java Arrays
• Normally, an array is a collection of similar type of elements which has
contiguous memory location.
• Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous
memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at
the 0th index, 2nd element is stored on 1st index and so on.
• Unlike C/C++, we can get the length of the array using the length
member. In C/C++, we need to use the sizeof operator.
• Like C/C++, we can also create single dimentional or multidimentional
arrays in Java.
• Moreover, Java provides the feature of anonymous arrays which is not
available in C/C+
Declaration, Instantiation and
Initialization of Java Array //
Java Program to illustrate the use of d
int a[]={33,3,4,5};// eclaration, instantiation
declaration, instantiation and init //
ialization and initialization of Java array in a sin
gle line
class Testarray1{
public static void main(String args[]
){
int a[]={33,3,4,5};//
Output:
declaration, instantiation and initializa
33 tion
3 //printing array
4 for(int i=0;i<a.length;i++)//
5 length is the property of array
System.out.println(a[i]);
Single Dimensional Array in //
Java Java Program to illustrate how to declar
e, instantiate, initialize
Syntax to Declare an Array //and traverse the Java array.
in Java class Testarray{
dataType[] arr; (or) public static void main(String args[])
dataType []arr; (or) {
dataType arr[]; int a[]=new int[5];//
declaration and instantiation
Instantiation of an Array in a[0]=10;//initialization
Java a[1]=20;
a[2]=70;
arrayRefVar=new datatype[size
Output:
a[3]=40;
]; 10 a[4]=50;
20 //traversing array
70
40
for(int i=0;i<a.length;i++)//
50 length is the property of array
System.out.println(a[i]);
Anonymous Array in Java
Java supports the feature of an anonymous
array, so you don't need to declare the array
while passing an array to the method.

//
Java Program to demonstrate the way of passi
ng an anonymous array
//to method.
public class TestAnonymousArray{
//
creating a method which receives an array as
a parameter
static void printArray(int arr[]){ Output:
for(int i=0;i<arr.length;i++) 10
System.out.println(arr[i]); 22
} 44
66
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//
passing anonymous array to method
Multidimensional Array //
in Java Java Program to illustrate the use of multidimensio
In such case, data is stored nal array
in row and column based class Testarray3{
public static void main(String args[]){
index (also known as matrix
//declaring and initializing 2D array
form). int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
Syntax: dataType[] for(int i=0;i<3;i++){
[] arrayRefVar; (or) for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
dataType []
}
[]arrayRefVar; (or) System.out.println();
dataType arrayRefVar[] }
[]; (or) }}
Output
dataType []arrayRefVar[]; 123
245
445
Example to instantiate
Multidimensional Array
in Java
Java String
In Java, string is basically an object that represents sequence of
char values. An array of characters works same as Java string.
For example:

char[] ch={'j','a','v','a',’s',’u',’b’,’j',’e’,’c’,'t'};
String s=new String(ch);

is same as:
String s="javasubject";

Java String class provides a lot of methods to perform


operations on strings such as compare(), concat(), equals(),
split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces

CharSequence Interface
• The CharSequence interface is used to represent the sequence of
characters.
• String, StringBuffer and StringBuilder classes implement it. It means,
we can create strings in Java by using these three classes.
• The Java String is immutable which means it cannot be changed.
Whenever we change any string, a new instance is created.
• For mutable strings, you can use StringBuffer and StringBuilder classes.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an
object that represents a sequence of characters. The java.lang.String class
is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal 2. By new keyword
1) String Literal
Java String literal is created by using double
quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM
checks the "string constant pool (special memory In this example, only one object
area)" first. If the string already exists in the pool, will be created. Firstly, JVM will
not find any string object with
a reference to the pooled instance is returned. If the value "Welcome" in string
constant pool that is why it will
the string doesn't exist in the pool, a new string create a new object. After that
instance is created and placed in the pool. For it will find the string with the
value "Welcome" in the pool, it
example: will not create a new object but
2) By new keyword

String s=new String("Welcome");//


creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//
creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//
converting char array to string
String s3=new String("example");//
creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
Output:
}}java The above code, converts
a char array into a String object. And
strings
displays the String objects s1, s2,
example
and s3 on console
using println() method.
No. Method Description
1 char charAt(int index) It returns char value for the particular index
2 int length() It returns string length
3 static String format(String format, Object... args) It returns a formatted string.
4 static String format(Locale l, String format, Object... args) It returns formatted string with given locale.
5 String substring(int beginIndex) It returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after matching the sequence of char
value.
8 static String join(CharSequence delimiter, CharSequence... elements) It returns a joined string.

9 static String join(CharSequence delimiter, Iterable<? extends CharSe It returns a joined string.
quence> elements)
10 boolean equals(Object another) It checks the equality of string with the given object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified string.
13 String replace(char old, char new) It replaces all occurrences of the specified char value.
14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It doesn't check case.
16 String[] split(String regex) It returns a split string matching regex.
17 String[] split(String regex, int limit) It returns a split string matching regex and limit.
18 String intern() It returns an interned string.
19 int indexOf(int ch) It returns the specified char value index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting with given
index.
21 int indexOf(String substring) It returns the specified substring index.
22 int indexOf(String substring, int fromIndex) It returns the specified substring index starting with given
index.
23 String toLowerCase() It returns a string in lowercase.
24 String toLowerCase(Locale l) It returns a string in lowercase using specified locale.
25 String toUpperCase() It returns a string in uppercase.
26 String toUpperCase(Locale l) It returns a string in uppercase using specified locale.
27 String trim() It removes beginning and ending spaces of this string.
28 static String valueOf(int value) It converts given type into string. It is an overloaded method.
Wrapper classes in Java
• The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature convert primitives
into objects and objects into primitives automatically. The automatic
conversion of primitive into an object is known as autoboxing and vice-
versa
Use unboxing.
of Wrapper classes in Java
• Java is an object-oriented programming language, so we need to deal with objects
many times like in Collections, Serialization, Synchronization, etc. Let us see the
different scenarios, where we need to use the wrapper classes.
• Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through the
wrapper classes.
• Synchronization: Java synchronization works with objects in Multithreading.
• java.util package: The java.util package provides the utility classes to deal with
objects.
• Collection Framework: Java collection framework works with objects only. All
The eight classes of the java.lang package are known as wrapper classes
in Java. The list of eight wrapper classes are given below:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
Autoboxing
• The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char
to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
• Since Java 5, we do not need to use the valueOf() method of wrapper
classes to convert the primitive into objects.
//
Java program to convert primitive into objects
Output
//Autoboxing example of int to Integer 20 20 20
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//
converting int into Integer explicitly
Integer j=a;//
autoboxing, now compiler will write Integer.va
lueOf(a) internally
Unboxing
• The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing.
• Since Java 5, we do not need to use the intValue() method of wrapper
//classes to convert the wrapper type into primitives.
Java program to convert object into pr
imitives
Output
//Unboxing example of Integer to int 333
public class WrapperExample2{
public static void main(String args[]
){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//
converting Integer to int explicitly
int j=a;//
//
Autoboxing: Converting primitives into obje
// cts
Java Program to convert all primitives into Byte byteobj=b;
its corresponding Short shortobj=s;
//wrapper objects and vice-versa Integer intobj=i;
public class WrapperExample3{ Long longobj=l;
public static void main(String args[]){ Float floatobj=f;
byte b=10; Double doubleobj=d;
short s=20; Character charobj=c;
int i=30; Boolean boolobj=b2;
long l=40;
float f=50.0F; //Printing objects
double d=60.0D; System.out.println("---
char c='a'; Printing object values---");
boolean b2=true; System.out.println("Byte object: "+byteobj);

System.out.println("Short object: "+shortobj


);
System.out.println("Integer object: "+intobj
);
//
Unboxing: Converting Objects to Primitives
---Printing object values---
Byte object: 10
byte bytevalue=byteobj;
Short object: 20
short shortvalue=shortobj;
Integer object: 30
int intvalue=intobj;
Long object: 40
long longvalue=longobj;
Float object: 50.0
float floatvalue=floatobj;
Double object: 60.0
double doublevalue=doubleobj;
Character object: a
char charvalue=charobj;
Boolean object: true
boolean boolvalue=boolobj;
---Printing primitive values---
byte value: 10
//Printing primitives
short value: 20
System.out.println("---
int value: 30
Printing primitive values---");
long value: 40
System.out.println("byte value: "+bytevalu
float value: 50.0
e);
double value: 60.0
System.out.println("short value: "+shortval
char value: a
ue);
boolean value: true
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalu
e);
Inheritance in Java
• 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


•For Method Overriding (so runtime polymorphism can be achieved).
•For Code Reusability.
Terms used in Inheritance

Class: A class is a group of objects which have common


properties. It is a template or blueprint from which objects
are created.

Sub Class/Child Class: Subclass is a class which inherits


the other class. It is also called a derived class, extended
class, or child class.

Super Class/Parent Class: Superclass is the class from


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

Reusability: As the name specifies, reusability is a


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.
class Employee{
float salary=40000; In this example,
} Programmer object
can access the field of
class Programmer extends Employee{ own class as well as of
int bonus=10000; Employee class i.e.
public static void main(String args[]){ code reusability.
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+
p.salary);
System.out.println("Bonus of Programmer is:
"+p.bonus); Output:
} Programmer salary is:40000.0
Bonus of programmer is:10000
}
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.
When one class inherits multiple classes, it is known as multiple
inheritance. For Example:

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


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.
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[] Output:
){ barking...
Dog d=new Dog(); eating...
d.bark();
d.eat();
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.
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep() Output:
{System.out.println("weeping...");}
weeping...
}
class TestInheritance2{ barking...
public static void main(String args[]) eating...
{
BabyDog d=new BabyDog();
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.
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class Cat extends Animal{
void meow()
{System.out.println("meowing...");}
} Output:
class TestInheritance3{ meowing...
public static void main(String args[]) eating...
{
Cat c=new Cat();
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
class C extends A,B{//suppose if it were
method or different, there will be compile time error.
class A{ public static void main(String args[]){
void msg() C obj=new C();
{System.out.println("Hello");} obj.msg();//
} Now which msg() method would be invoked?
class B{ }
void msg() }
{System.out.println("Welcome");}
Output:
} Compile Time Error
Constructors in Derived Class:

• Constructors in Java are used to initialize the values of the attributes of the object
serving the goal to bring Java closer to the real world.

• We already have a default constructor that is called automatically if no constructor is


found in the code.

• But if we make any constructor say parameterized constructor in order to initialize


some attributes then it must write down the default constructor because it now will
be no more automatically called.

Note: In Java, constructor of the base class with no argument gets automatically
called in the derived class constructor.
// Java Program to Illustrate Invocation of
Constructor Calling Without Usage of super
Keyword // Class 3
// Main class
// Class 1 Super class class GFG {
class Base { // Main driver method
// Constructor of super class public static void main(String[]
Base() args)
{
{
// Print statement
System.out.println( // Creating an object of sub
"Base Class Constructor Called "); class
} // inside main() method
// Class 2 Derived d = new Derived();
// Sub class // Note: Here first super
class Derived extends Base { class constructor will be
// called there after
// Constructor of sub class derived(sub class)Outputconstructor
Derived() // will beBase called
Class Constructor Called
{ } Derived Class Constructor Called
// Print statement }
System.out.println( Output Explanation: Here first superclass
"Derived Class Constructor Called constructor will be called thereafter derived(sub-
"); class) constructor will be called because the
}
constructor call is from top to bottom.
}
// Java Program to Illustrate Invocation of
Constructor Calling With Usage of super Keyword
// Class 3 Main class
// Class 1 Super class
class Base {
public class GFG {
int x; // Main driver method
// Constructor of super class public static void main(String[] args)
Base(int _x) { x = _x; } {
} // Creating object of sub class
// Class 2 Sub class // inside main() method
class Derived extends Base { Derived d = new Derived(10, 20);
int y;
// Invoking method inside main()
// Constructor of sub class
Derived(int _x, int _y) method
{ d.Display();
// super keyword refers to super class }
super(_x); } Output
y = _y; x = 10, y = 20
}
// Method of sub class
Here we call a parameterized constructor of
void Display()
{
the base class using super(). The point to
// Print statement note is base class constructor call must
System.out.println("x = " + x + ", y = " be the first line in the derived class
+ y); constructor.
}
} Implementation: super(_x) is the first line-
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.
• 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


• Method overriding is used to provide the specific implementation of
a method which is already provided by its superclass.
• Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding
//
Java Program to demonstrate why we need met
hod overriding.Here, we are calling the method
of parent class with child class object.
//Creating a parent class
class Vehicle{
void run()
{System.out.println("Vehicle is running");}
} Output:
//Creating a child class Vehicle is running
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Problem is that we have to
Bike obj = new Bike();
provide a specific
//calling the method with child class instance
implementation of run()
obj.run();
method in subclass that is why
}
we use method overriding.
}
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 name and parameter of
the method are the same, and there is IS-A relationship between the classes, so
there is method overriding.
//
Java Program to illustrate the use of Java Method O
verriding
//Creating a parent class.
class Vehicle{
//defining a method Output:
void run() Bike is running safely
{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
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.
// //
Java Program to demonstrate the real s Test class to create objects and call the m
cenario of Java Method Overriding wher ethods
e three classes are overriding the meth class Test2{
od of a parent class. public static void main(String args[]){
SBI s=new SBI();
//Creating a parent class. ICICI i=new ICICI();
class Bank{ AXIS a=new AXIS();
int getRateOfInterest(){return 0;} System.out.println("SBI Rate of Interest: "
} +s.getRateOfInterest());
//Creating child classes. System.out.println("ICICI Rate of Interest:
"+i.getRateOfInterest());
class SBI extends Bank{ System.out.println("AXIS Rate of Interest:
int getRateOfInterest(){return 8;} "+a.getRateOfInterest());
} }
}
class ICICI extends Bank{ Output:
SBI Rate of Interest: 8
int getRateOfInterest(){return 7;}
ICICI Rate of Interest: 7
} AXIS Rate of Interest: 9
class AXIS extends Bank{

You might also like