Method Overriding, Abstract Class and Interface in Java
Method Overriding, Abstract Class and Interface in Java
Interface in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
2
METHOD OVERRIDING
5
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}}
class B extends A
{
void m1() // overriding m1()
{
System.out.println("Inside B's m1 method");
}}
class C extends A
{
void m1() // overriding m1()
{
System.out.println("Inside C's m1 method");
}}
class Dispatch
{
public static void main(String args[])
{ A a = new A();
B b = new B();
C c = new C(); 6
// obtain a reference of type A
A ref;
8
ABSTRACT 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();
} } 9
OBJECT CLASS
● 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 when want to refer
any object whose type you don't know.
● Parent class reference variable can refer the child
class object, know as upcasting.
● Methods of object class are inherited by every
object created in a Java program.
10
11
12
13
14
15
The equals( ) method compares two object reference, to see whether they refer to the same object
16
toString( ) method
18
Program : With Overriding toString
19
INTERFACE
20
INTERFACE
24-01-2021 21
INTERFACE (cont…)
22
interface Bank {
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest() { return 9.15f; }
}
class ICICI implements Bank{
public float rateOfInterest() { return 9.7f; }
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest()); }} 23
interface Printable{
public static void main(String args[])
void print(); }
{
interface Showable extends Printable
TestInterface4 obj = new TestInterface4();
{
void show();
obj.print();
}
obj.show();
class TestInterface4 implements Showable
}
{
}
public void print()
{System.out.println("Hello");}
System.out.println("Welcome");
}
24
25
26
NESTED INTERFACE
●
Nested interface must be public if it is declared
inside the interface but it can have any access
modifier if declared within the class.
●
Nested interfaces are declared static implicitly.
27
NESTED INTERFACE
Syntax of nested interface which is declared within the interface
interface interface_name{
...
interface nested_interface_name{
...
}
}
28
NESTED INTERFACE
class class_name{
...
interface nested_interface_name{
...
29
30