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

后端 未结 6 1291
离开以前
离开以前 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:54

    In both the cases, objects of subClass will be created, but the references will be different.

    With the reference of superClass i.e sc1 , you won't be able to invoke the methods present in the subClass but not in the superClass. You will require casting to invoke the subClass methods.

    Like :

    class superClass {
       public void superClassMethod(){
       }
    }
    
    class subClass extends superClass{
       public void subClassMethod(){
       }
    }
    

    Now :

    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?
    
    
        sc2.subClassMethod(); //this is valid
    
        sc1.subClassMethod(); // this is a compiler error, 
                              // as no method named subClassMethod
                              // is present in the superClass as the
                              // reference is of superClass type
    
       // for this you require a type cast
    
       (subClass)sc1.subClassMethod(); // Now this is valid
    
      }
    }
    

提交回复
热议问题