MBZ
MBZ

Reputation: 27592

Get the "child" object's Class in a final method?

is it possible to access child class in parent?

e. g. I want the output of the following code tobe "red blue".

class Color {
    public final void printName() {
        System.out.println(__Something_Here!!!__.class.getSimpleName());
    }
}

class Red extends Color;

class Blue extends Color;

main() {
    Red red = new red();
    Blue blue = new blue();
    red.printName();
    blue.printName();
}

Upvotes: 2

Views: 192

Answers (3)

gobernador
gobernador

Reputation: 5739

Not if you make printName() private. If it is protected, then you can call

Red red = new Red();
Blue blue = new Blue();
red.printName();
blue.printName();

and then call

System.out.println(this.class.getSimpleName());

As it is, private prohibits Red and Blue from inheriting the method.

Upvotes: 0

NamshubWriter
NamshubWriter

Reputation: 24286

You can use getClass() to return the class object for any object.

public final void printName() {
    System.out.println(getClass().getSimpleName());
}

See the Javadoc for getClass() for details

Upvotes: 1

dash1e
dash1e

Reputation: 7807

Write

class Color {
    public final void printName() {
        System.out.println(this.getClass().getSimpleName());
    }
}

Every Java object by getClass() method can access all the class info.

Upvotes: 1

Related Questions