Dylan Deshler
Dylan Deshler

Reputation: 59

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.

Upvotes: 1

Views: 69

Answers (3)

Kevin
Kevin

Reputation: 1363

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();
    }
}

Upvotes: 0

ROOT
ROOT

Reputation: 1775

        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.

Upvotes: 1

Andreas
Andreas

Reputation: 159086

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!");
    }
}

Upvotes: 5

Related Questions