简体   繁体   中英

Can I access a subclass method through a base class-typed reference?

Below is the piece of code I am trying to work on but unable to sort out the issue: "Can I really do the below in Java.. If yes please help to know me "How" and if no "Why?" "... Have a look at the code below...

class Base{

      public void func(){

            System.out.println("In Base Class func method !!");         
      };
}

class Derived extends Base{

      public void func(){   // Method Overriding

            System.out.println("In Derived Class func method"); 
      }

      public void func2(){  // How to access this by Base class reference

            System.out.println("In Derived Class func2 method");
      }  
}

class InheritDemo{

      public static void main(String [] args){

            Base B= new Derived();
            B.func2();   // <--- Can I access this ??? This is the issue...
      }
}

Thanks in advance!!!! Waiting for some helpful answers :) ...

short and sweet? No you cant.. How must Base know what functions/methods are present in the extended class?

EDIT:

By explict/type casting, this may be achieved, as the compiler takes it you know what you are doing when casting the object Base to Derived :

if (B instanceof Derived) {//make sure it is an instance of the child class before casting
((Derived) B).func2();
}

因为B不知道func2,所以它甚至不会编译

Since the type of object B is Base and the Base type doesn't have a func2() in its public interface, your code is not going to compile.

You can either define B as Derived or cast the B object to Derived:

   Derived B = new Derived(); B.func2();
   //or
   Base B = new Derived(); ((Derived)B).func2();

You can do

((Derived) B).func2(); 

You can't do

B.func2(); 

as func2 is not a method of the Base class.

像这样:

((Derived) B).func2();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM