Reputation: 233
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.
Upvotes: 1
Views: 1569
Reputation: 539
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.
Upvotes: 0
Reputation: 234885
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.
Upvotes: 2
Reputation: 39
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().
Upvotes: 0