1

下面是我正在尝试处理但无法解决问题的一段代码:“我真的可以在 Java 中执行以下操作吗.. 如果是,请帮助了解我“如何”,如果没有“为什么?”。 ..看看下面的代码...

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...
      }
}

提前致谢!!!!等待一些有用的答案:) ...

4

5 回答 5

4

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();
}
于 2012-08-15T18:53:55.270 回答
2

This wont even compile as B is unaware of the func2

于 2012-08-15T18:52:11.760 回答
2

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();
于 2012-08-15T18:54:11.450 回答
1

You can do

((Derived) B).func2(); 

You can't do

B.func2(); 

as func2 is not a method of the Base class.

于 2012-08-15T18:54:10.933 回答
0

像这样:

((Derived) B).func2();
于 2012-08-15T18:54:17.977 回答