I'm unable to perform virtual method invocation
This is my code:
class base1
{
}
class der1 extends base1
{
public static void main(String []args)
{
base1 b=new der1();
b.showTest();
}
public void showTest()
{
System.out.println("Hello i am a der开发者_如何学Pythonive class");
}
}
it will not compile.
you need showTest()
in base class also to make it compilable
base1 b=new der1(); b.showTest();
here b
is the reference of base
, you need showTest()
in base
at compile time it wil check for showTest()
in base
and at run time due to
base1 b=new der1();
it will invoke der1
's version of showTest()
Also See
- Polymorphism
The method showTest()
is defined in the subclass. To be able to use it you have to:
1.- Declare it in the base class
class base1 {
public void showTest(){
}
}
Or
2.- Declare b
as der1
public static void main( String [] args ) {
der 1 b = new der1();
...
精彩评论