0

Suppose a class MyClass implements an interface MyInterface, and it has its own instance method let's say foo(). When i create an instance of MyClass like this:

MyInterface myClass = new MyClass();

The compiler wouldn't let me access its instance method without an explicit casting:

myClass.foo();  // Can't resolve symbol
((MyClass) myClass).foo(); // this is okay

Even though the compiler obviously knows myClass is an instance of MyClass:

if(myClass instanceof MyClass)
  System.out.println(myClass.getClass().getName()); //this will print "MyClass"

Why do i need to use cast for compiler to allow me to access the instance method?

  • 3
    Because **you told** the compiler to treat `myClass` as a `MyInterface` instance, so it can only access `MyInterface` methods. The compiler is doing what you asked it to do. If you want to call `MyClass` methods (without casting), then you would use a `MyClass`-type variable. – khelwood Aug 31 '20 at 22:25
  • Does this answer your question? [What is the difference between up-casting and down-casting with respect to class variable](https://stackoverflow.com/questions/23414090/what-is-the-difference-between-up-casting-and-down-casting-with-respect-to-class) – PM 77-1 Aug 31 '20 at 22:26
  • This demonstrates polymorphism. You can treat instances of MyClass as MyClass, My instance or Object depending on the type of the variable declaration – Jon H Aug 31 '20 at 22:33

2 Answers2

2

The meaning of the line MyInterface myClass = new MyClass() is, "Create a new MyClass, and then forget about all its features except those defined in the interface MyInterface."

When you refer to "the compiler obviously knows myClass is an instance of MyClass," you're not actually correct: it's not the compiler that knows that, but the runtime. The compiler was told to forget that information, and it did.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

It might be of type MyClass but you are treating it as a MyInterface. When you do A myVar = new B(); you only have access to whatever you can access in A even though myVaris of type B.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24