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
}
nao
  • 1,128
  • 1
  • 14
  • 37
  • "If I use t.getClass()" - well, what happens when you try? – D M Mar 23 '17 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. – Timothy Truckle Mar 23 '17 at 20:31
  • Possible duplicate of [How to find out the subclass from the base class instance?](http://stackoverflow.com/questions/2856122/how-to-find-out-the-subclass-from-the-base-class-instance) – Mike Nakis Mar 23 '17 at 22:00

2 Answers2

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
}
Peyman Mahdian
  • 522
  • 4
  • 15
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.

Sandeep Kaul
  • 2,957
  • 2
  • 20
  • 36