0

I am a new java programmer.

I have following hierarchy of classes:

public interface base

public interface Object1Type extends base

public interface Object2Type extends Object1Type

public class Object3Type implements Object2Type
{ 
      byte[] value;
} 

I have another class where I have an object of Object1Type a;

can I access byte[] value member of Object3Type type using this object a?

Ek1234
  • 407
  • 3
  • 7
  • 17
  • You would have to cast to `Object3Type` – ernest_k Mar 25 '19 at 05:26
  • 1
    It is not a good practice for parents to know about children and siblings to know about each other. – vavasthi Mar 25 '19 at 05:27
  • You *shouldn't*. If you need to know about the fact that `value` exists, then your code needs to express that need by using the correct type. In some cases, it might be appropriate to define an extra interface `HasValue` to represent this concept. – chrylis -cautiouslyoptimistic- Mar 25 '19 at 05:32

1 Answers1

2

You can use class cast:

public static void main(String args[]) {
    Object1Type a = new Object3Type();

    if (a instanceof Object3Type) {
        Object3Type b = (Object3Type) a;
        byte[] bytes = b.value;
    }
}

But it's dangerous and not recommended practice. The responsibility for cast correctness lies on a programmer. See example:

class Object3Type implements Object2Type {
    byte[] value;
}

class Object4Type implements Object2Type {
    byte[] value;
}

class DemoApplication {

    public static void main(String args[]) {
        Object1Type a = new Object3Type();

        Object3Type b = (Object3Type) a; // Compiles and works without exceptions
        Object4Type c = (Object4Type) a; // java.lang.ClassCastException: Object3Type cannot be cast to Object4Type
    }
}

If you do it, at least check an object with the instanceof operator previously.

I'll recommend you to declare some getter in one of the interfaces (existing or new) and implement this method in the class:

interface Object1Type extends Base {
    byte[] getValue();
}

interface Object2Type extends Object1Type {}

class Object3Type implements Object2Type {
    byte[] value;

    public byte[] getValue() {
        return value;
    }
}

class DemoApplication {

    public static void main(String args[]) {
        Object1Type a = new Object3Type();
        byte[] bytes = a.getValue();
    }
}
ilinykhma
  • 980
  • 1
  • 8
  • 14