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

后端 未结 6 1249
离开以前
离开以前 2021-01-03 05:14
class superClass {}

class subClass extends superClass{}

public class test
{

    public static void main()

{

    superClass sc1 = new subClass();
    subClass sc         


        
6条回答
  •  隐瞒了意图╮
    2021-01-03 05:58

    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.
    

提交回复
热议问题