Reputation: 415
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 :) ...
Upvotes: 1
Views: 9875
Reputation: 36423
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();
}
Upvotes: 4
Reputation: 10093
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();
Upvotes: 2
Reputation: 533500
You can do
((Derived) B).func2();
You can't do
B.func2();
as func2 is not a method of the Base class.
Upvotes: 1