0

I want to access the parent's member function from the child's reference variable.

My code :

class Emp
{
static String Cname="Google";
int salary ;
String Name;

void get(String s1,int s2)
{
    Name=s1;
    salary=s2;
}
void show()
{
    System.out.println(Name);
    System.out.println(salary);
    System.out.println(Cname);

}

}
public class Practice extends Emp{

/**
 * @param args
 */
void show()
{
    System.out.println("in Child class");
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Practice e=new Practice();
    e.show();
    e.get("Ratan",200000);
    ((Emp)e).show();
}

} 

The output is :

in Child class
in Child class

which means both times the child's member function is being called. What would be the way to sort this out?

Leigh
  • 28,765
  • 10
  • 55
  • 103
Ratan Kumar
  • 1,640
  • 3
  • 25
  • 52

3 Answers3

0

You have to call the superclass's method like this : super.show();

Zakaria
  • 14,892
  • 22
  • 84
  • 125
0

It's impossible outside of the child class. (Inside child class use super.show()).

mart
  • 2,537
  • 1
  • 15
  • 13
0

You can't really do what you're trying to do. As others have said, WITHIN the subclass you can call base class methods using super.methodName();

So you could write a method inside your Practice class thus: showBase() { super.show(); } but that somewhat defeats the point of overriding show() in the first place.

You either want to change the behaviour of a method in a base class with overrides or have extra methods in your subclass to enrich the functionality of the base class. To try and do what you suggest indicates that you need to rethink your design.

Steve Atkinson
  • 1,219
  • 2
  • 12
  • 30