简体   繁体   中英

Can I use a method from a super class in a subclass without overriding it?

I'm sure this is a simple question but I don't know the answer. First of all, is it possible to do something like this?

public class Entity {


public void sayHi() {
        System.out.println(“Hi there!”);
    }
}

public class Person extends Entity {
    public void sayHi() {
        System.out.println(“I’m a person!”);
    }
}

Where the print out would be: HI there! I'm a person! This is just an example, but is this possible? If so how do I do it? Because for this, the actual printout would be "I'm a person!". Would the sayHi() method in Person have to have its own printout that says "Hi There!" in order for this to work?

If you have any questions leave a comment and I will do my best. Thanks.

Yes, you just call the method in the superclass from the method in the subclass.

See The Java™ Tutorials - Using the Keyword super .

public class Entity {
    public void sayHi() {
        System.out.println("Hi there!");
    }
}
public class Person extends Entity {
    @Override
    public void sayHi() {
        super.sayHi();
        System.out.println("I’m a person!");
    }
}
        public class Entity {
        public void sayHi() {
            System.out.print("Hi there!");

        }
    }
    public class Person extends Entity {
        super.sayHi();
System.out.print("I’m a person!");
    }

I think this may helps you.

Regarding Andreas's anwser, there is a way without add 'super' by java reflection:

public class Entity {
    public void sayHi() {
        System.out.println("Hi there!");
    }
}

public class Person extends Entity {
    public void sayHi() {
        System.out.println("I’m a person!");
    }
}

public class Tester {
    public static void main(String[] args) throws Throwable {
        Person x = new Person();
        MethodHandle h1 = MethodHandles.lookup().findSpecial(x.getClass().getSuperclass(), "sayHi",
                MethodType.methodType(void.class),
                x.getClass());

        h1.invoke(x);
        x.sayHi();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM