Class A
has run()
method and interface B also has run()
method. Question is simple, which run()
method is overridden in Main
class and how will we prove this? Why there is no conflict (Compile-time error) in this code?
class A{ void run(){System.out.println("A class");} } interface B{ void run(); } class Main extends A implements B{ public static void main(String args[]){ Main m = new Main(); m.run(); } // Overridding method public void run(){ System.out.println("run method"); } }
The duplicate() method of java. nio. CharBuffer Class is used to Create a new char buffer that shares the given buffer's content. The content of the new buffer will be that of this buffer.
Sonar uses the following four metrics to cover code duplication. Duplicated lines can also be expressed as a percentage value and we will create an alert with a threshold value of five percent. Number of physical lines touched by duplication. Number of duplicated blocks participating in duplication.
getMethod("myMethod"). getDeclaringClass(); If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it.
A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
run
of A
is overridden, run
of B
is implemented. As B
is an interface, it only states how your objects behave to others and don't enforce any behavior itself.
run()
Method of Interface B will be Implemented in class Main by overridden method of Class A.
Adding an extra point,
It you will not write the run()
method in child class Main
, You will not get well known "Unimplemented methods" error. This is true for public
methods of class A for non public methods you will get compiler error : The inherited method can not hide public abstract method.
That is because methods of interface are public by default and you can not hide it with default (package private)
access modifier.
Sample :
class A{ public void run() { System.out.println("This method will be inherited."); } } interface B{ void run(); } class Main extends A implements B{ public static void main(String args[]){ Main m = new Main(); m.run(); } }
OUTPUT : This method will be inherited.
In above code instance, the run()
method is inherited from class A that will implement run()
method of interface B.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With