简体   繁体   中英

Extending a non abstract class and implementing an interface with same method signatures in a class

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.

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.

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().

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM