Đặng Võ
Đặng Võ

Reputation: 23

Is there different between this two ways of creating an object

I just have learned java. I'm fiding the different between this both ways of creating an object

public class A {
}
public class B extends A {
}
public static void main(String[] args){
       A object = new B();
       B object = new B();
}

Upvotes: 2

Views: 74

Answers (1)

Innovation
Innovation

Reputation: 1524

Lets understand it with the example below.

  1. In class A we added a getMethodofA(). So creating reference variable as A or B does not matter. As A is super class getMethodofA() will be available for both the objects of Type A or Type B

  2. In class B we added a getMethodofB(). So creating reference variable as A or B matters. If you create object with reference variable as A, then only getMethodofA() will be available. While If you create object with reference variable B both the methods will be visible getMethodofA() and getMethodofB()

    public class A {
    
         public void getMethodofA(){
             System.out.println("I am method A")
         }
    
    }
    
    public class B extends A {
         public void getMethodofB(){
            System.out.println("I am method B")
        }
    }
    
    public static void main(String[] args){
        A objectA = new B();
        objectA.getMethodofA();//No error
        objectA.getMethodofB();//Compile time error
    
        B objectB = new B();
        objectB.getMethodofA();//No error
        objectB.getMethodofB();//No error
    }
    

Upvotes: 2

Related Questions