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
  • 389
  • 3
  • 6
  • 17

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
  • 940
  • 1
  • 8
  • 14