Search code examples
javainheritanceambiguity

How to call function with same name from an inherited class in java


I am new to java and I remember in c++ we did something like CLASSNAME::Fn() to avoid ambiguity in inheritance.

Here's my code and I want to have same display methods in both classes and access them explicitly.

public class Main {
    public static void main(String args[]){
    Emplo e = new Emplo("samuel",19,"designer",465);
    e.display();  // here i want to call both display()
    }
}

public class Person {
    String name;
    int age;

    Person(String s, int a){
        name = s;
        age = a;
    }

    public void dispaly(){
        System.out.println("name: "+name+"\nage: "+age);
    }
}


public class Emplo extends Person {
    String desg;
    double sal;
    Emplo(String s,int a,String d, double sa){
        super(s,a);
        desg=d;
        sal=sa;
    }
    void display(){
        System.out.println("desg: "+desg+"\nsal: "+sal);
    }
}

Solution

  • In java, you can't not call the specific method implementation of the class of the instance.

    That is, you can't "bypass" a sub-class method and call a super-class version of the method; calling the super-class method can only be done from within the subclass using super.someMethod().

    You can't even invoke a super-super class's version, ie you can't do something like super.super.someMethod()