1

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 :) ...

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
AnkitChhajed
  • 415
  • 2
  • 6
  • 9

5 Answers5

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();
}
dimo414
  • 47,227
  • 18
  • 148
  • 244
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
2

This wont even compile as B is unaware of the func2

srikanth yaradla
  • 1,225
  • 10
  • 13
  • thanks for replying.. But that is what i Want to ask .. Can I make B aware of it anyhow ?? As i can using pointers in C++ but how can i do it here in java??? – AnkitChhajed Aug 15 '12 at 18:56
  • Base class is not aware of the methods specific to Derived.You can only access derived class methods by type casting to Dervied like `((Derived) B).func2();` – srikanth yaradla Aug 15 '12 at 19:00
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();
Razvan
  • 9,925
  • 6
  • 38
  • 51
1

You can do

((Derived) B).func2(); 

You can't do

B.func2(); 

as func2 is not a method of the Base class.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Like this:

((Derived) B).func2();
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111