0

I wasn't quite sure how to word it in the title, but here is the use case.

I have a class Test. Test has an attribute called Letter as so

public class Test() { Letter x; } 

Letter can be one of several subclasses.

class A() class B() class C() 

Now suppose that in a class (let's call it driver), I have an instance of Test. I want to figure out whether this Test's letter is A, B, C, etc. so that I can access attribute unique to the child class. See:

public class Driver() { Test t; } 

If I use t.getClass(), will I get Class.Test, or will I get the child class (e.g. Class.A)? Is it possible for the Driver class to know x's subclass?

Is it possible to create a method like:

public Class getSubclassFromLetter(Letter x) { // Find subclass from the letter } 
3
  • "If I use t.getClass()" - well, what happens when you try? Commented Mar 23, 2017 at 20:30
  • 1
    "so that I can access attribute unique to the child class." Then your design is bad. One of the most important OO principles is information hiding which basically means that no other class knows what properties an object has. Commented Mar 23, 2017 at 20:31
  • Possible duplicate of How to find out the subclass from the base class instance? Commented Mar 23, 2017 at 22:00

2 Answers 2

2

You can use instanceof. It is not really a good practice to do that, but you can do the following:

if (x instanceof A) { //TODO whatever related to A } 
Sign up to request clarification or add additional context in comments.

Comments

1

using either instanceof or Class#getClass()

A returned = getA(); if (returned instanceof B) { .. } else if (returned instanceof C) { .. } 

getClass() would return either of: A.class, B.class, C.class

That said, sometimes it is considered that using instanceof or getClass() is a bad practice.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.