Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between subClass sc = new subClass() and superClass sc = new subClass?

class superClass {}

class subClass extends superClass{}

public class test
{

    public static void main()

{

    superClass sc1 = new subClass();
    subClass sc2 = new subClass();
    //whats the difference between the two objects created using the above code?

}
}
like image 409
flav Avatar asked Dec 08 '22 16:12

flav


2 Answers

Simple explanation : When you use

SuperClass obj = new SubClass();

Only public methods that are defined in SuperClass are accessible. Methods defined in SubClass are not.

When you use

SubClass obj = new SubClass(); 

public methods defined in SubClass are also accessible along with the SuperClass pubic methods.

Object created in both cases is the same.

Ex:

public class SuperClass {

  public void method1(){

  }
}

public class SubClass extends SuperClass {
  public void method2()
  {

  }
}

SubClass sub = new SubClass();
sub.method1();  //Valid through inheritance from SuperClass
sub.method2();  // Valid

SuperClass superClass = new SubClass();
superClass.method1();
superClass.method2(); // Compilation Error since Reference is of SuperClass so only SuperClass methods are accessible.
like image 110
Varun Achar Avatar answered May 22 '23 08:05

Varun Achar


whats the difference between the two objects created using the above code?

The two objects are exactly the same. What's different is the type of the variable where the object reference is stored. In practice, this means that if there are any methods specific to subClass, you'll be able to access them through sc2 but not through sc1 (the latter would require a cast).

like image 44
NPE Avatar answered May 22 '23 08:05

NPE