polymorphism

class A {
    public void test(){
        System.out.println("hello");
    }
    
    public void foo(){
        System.out.println("fooo");
    }
}

class B extends A {
    @Override
    public void test(){
        System.out.println("world");
    }
    public void bar(){
        System.out.println("baar");
    }
}


public class PolymorphismDemo {

    public static void main(String[] args) {
        
        A a = new A();
        a.test(); // allowed: will print hello
        a.foo(); // allowed: will print fooo
        //a.bar(); // not allowed: compile time error
        
        B b = new B();
        b.test(); // allowed: will print world
        b.foo(); // allowed: will print fooo
        b.bar(); // allowed: will print baar
        
        A c = new B();
        c.test(); // allowed: will print world
        c.foo(); // allowed: will print fooo
        //c.bar(); // not allowed: compile time error
        
        //B d = new A(); // not allowed: compile time error
        
        A e = new B();
        A f = (A)e;
        f.test(); // allowed: will print world
        f.foo(); // allowed: will print fooo
        //f.bar(); // not allowed: compile time error
        
        B g = new B();
        A h = (A)g;
        h.test(); // allowed: will print world
        h.foo(); // allowed: will print fooo
        //h.bar(); // not allowed: compile time error
    }    
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *