Advertisement
class A
{
}
class B extends A //class B is subclass/child class of class A
{
}
class Polymorphism
{
public static void main(String... ar)
{
//Object of B is accessed by reference variable of its own B class.
B ob1 = new B();
//Object of B is accessed by reference variable of its superclass, A.
A ob2 = new B();
//Object of B is accessed by reference variable of its superclass, Object.
Object ob3 = new B();
}
}
interface A
{
}
class B implements A //class B is implementing interface A, hence A is superclass of B
{
}
class Polymorphism
{
public static void main(String... ar)
{
//Object of B is accessed by reference variable of its own B class.
B ob1 = new B();
//Object of B is accessed by reference variable of its superclass, A.
A ob2 = new B();
//Object of B is accessed by reference variable of its superclass, Object.
Object ob3 = new B();
}
}
Advertisement
// Compile-time polymorphism - method overloading
class A //Superclass
{
public void message(A ob)
{
System.out.println("A");
}
}
class B extends A //Subclass
{
public void message(B ob) //overloaded message() method
{
System.out.println("B");
}
}
class Poly
{
public static void main(String... ar)
{
A ob1 = new B(); //ob1 is declared of type A but it is pointing to object of its subclass, B
ob1.message(ob1);
}
}
A
//Runtime polymorphism or dynamic method dispatch, during method overriding
class Vegetable //superclass
{
public void message()
{
System.out.println("Eat vegetables");
}
}
class Tomato extends Vegetable //subclass
{
public void message() //method message() of superclass Vegetable is overridden
{
System.out.println("Eat Tomatoes");
}
}
class Polymorphism
{
public static void main(String... ar)
{
Vegetable ob1= new Tomato(); //comment1
ob1.message(); //comment2
}
}
Eat Tomatoes
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement