Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am able to create a class object even when it is giving compilation error in Java

Tags:

java

java-7

Today, I came across a scenario where I have not overridden all the methods of the interface in the child class. However, when I tried to create an object of the child class, it still worked fine. My assumption so far is that we cannot create the objects unless all the compilation errors are resolved.

Please shed some light on this.

Example I have taken.

interface Parent {
   public void test();
}

class Child implements Parent {
   public void print() {
      System.out.println("Didn't expect to print");
   }
}

The Child class was giving me the compile time error asking me to override the methods from the interface. Ignoring the error, when I tried to create the object like below and execute the next statement, it gave me the output as indicated at the bottom.

Child child = new Child();
child.print();

Output:

Didn't expect to print

P.S: I tried this on Java 7

Please let me know if my basic understanding (that Java objects cannot be created without resolving compilation errors) is wrong

like image 245
Ravi Avatar asked Dec 20 '25 12:12

Ravi


1 Answers

This is only possible if your IDE cached the Child class before you added the Parent to it as a superclass. Otherwise this won't compile at all.

like image 62
Adam Arold Avatar answered Dec 22 '25 04:12

Adam Arold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!