1
votes

I have the following classes and interface

public class A {
  public void printSomething() {
    System.out.println("printing from A");
  }
}

interface B {
  public void printSomething();
}

public class C extends A implements B {
  public static void main(String aa[]) {
    C c = new C();
    c.printSomething();
  }
}

When I compile the above code, it compiles without any errors. And when I run the program it prints the following.

printing from A

I was expecting the compiler to give a similar error like the following error that I got when my class C did not extend class A

 C.java:1: error: C is not abstract and does not override abstract method printSomething() in B public class C implements B{
       ^
C.java:8: error: cannot find symbol
                        c.printSomething();
                         ^
  symbol:   method printSomething()
  location: variable c of type C
2 errors

I know that when a class implements an interface then we need to define the interface methods in the class or declare the class abstract. But then how just by extending a class (with a defined method of same signature) am I able to overcome this compiler warning and run the program as well.

3
It's because you are inheriting this method from the super class. The method has to be provided, and, through inheritance, it is - Stultuske
Why were you expecting this? Inheritance means that a C can be treated as an A; and A has that method... - Boris the Spider
implementing the interface forces you to have acces to the method defined in the interface in the class, not to actually have it written inside the class that does implement the interface. If the class does inherit from a class that did already define the method and it has access to it the conditions are fullfilled and hence you don“t need to overwrite the method again. - SomeJavaGuy

3 Answers

2
votes

It's absolutely fine to do that and is surprisingly common.

You are using class A as a tool for implementing the interface specified by interface B.

This sort of pattern facilitates modularisation and the potential for code reuse.

0
votes

This is because C is child of A. Whenever Child default contractor gets executed, its parent constructor gets called ( this is to inherit all the property of A ). In this case, "new C()" made all the property of A() available to class C including printSomething().

0
votes

This is because, by extending class A into class C, you actually providing implementation to the printSomething() method of interface B.

Please Note:,class A consist an implementation of printSomething() method.