This question already has answers here:
Interface and Abstract class ad method overriding
(3 answers)
Closed 8 years ago.
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");
}
}
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.
What will be called is
public void run(){
System.out.println("run method");
}
Why?
You're implementing run of interface B and you're also overriding the A implementation of it.
If you remove the last run() implementation and remove implements B, run() of A will be called.
Interface B says that any class implementing it must have a run method. Main extends A and inherits A's run() method.
Main meets the requirement of the B interface for having a run method. The run method in Main then overrides the run() method it got from the A class.
// This is a class with a run method.
class A{
void run(){System.out.println("A class");}
}
// Anything implementing this interface must have a run method.
interface B{
void run();
}
// This class is an extension of A (and therefore has A's run() method)
// This class implements B and must have a run method, which it does, because it has A's
class Main extends A implements B{
public static void main(String args[]){
Main m = new Main();
m.run();
}
// This method then overrides the run Method it inherited from A
// And this method meets the requirement set by implementing B.
public void run(){
System.out.println("run method");
}
}
There is no conflict because both methods have the same signature. Method declarations in interfaces are not overridden because they don't implement anything. So in this case, run method in class A is overridden.
On the other hand, when overriding methods you are encouraged to use the #Override annotation, e.g.
#Override
public void run() {
....
}
Super class's method is always called as overridden method whereas subclass method is called as overriding method.
Final method cannot be overridden. [if superclass's method is final]
Final methods can override. [Read it as grammatical way. This method is in subclass and is final, but superclass's method is not final]
Related
In the below program I had extended Demo1 class and implemented Demo interface and in Practice class I override public void demo() which was declared in both class and interface then from which that method will get Override? and why?
interface Demo{
void demo();
}
class Demo1{
int i=10;
public void demo() {
System.out.println("this is demo"+i);
}
}
public class practice extends Demo1 implements Demo {
public static void Main(String[] args ) {
practice p=new practice();
p.demo();
}
public void demo() {
System.out.println("This is Overrided method");
}
}
The short answer is that it doesn't matter. What the compiler is is looking for is that the signature of the abstract interface method is implemented in your class, or inherited from a supertype (and it doesn't care whether that inherited signature was meant to implement the abstract method in question). And whether your demo() method is called on a practice object declared as Demo or Demo1 is also irrelevant the method signature is implemented either way.
You can, in fact, even remove your demo() override (assuming you didn't need to change the behavior), and the code would still compile:
class practice extends Demo1 implements Demo {
public static void Main(String[] args) {
practice p = new practice();
p.demo();
}
}
That is, even if Demo1.demo() has nothing to do with Demo.demo(), the fact that practice inherits Demo1.demo() which has the same signature as Demo.demo() and without violating access and exception constraints, that makes practice a valid implementation of Demo.
Method from interface is not overrided, it's implemented.
Your practice class inherits the demo method from Demo1 class and this method will be used to implement Demo interface method if you omit the implementation of demo method in practice class itself.
Since you implement the demo method in practice class itself - this method overrides the method from Demo1 class and also implements the method from Demo interface
If you run the below code
public class practice extends Demo1 implements Demo {
public static void main(String[] args ) {
practice p=new practice();
p.demo();
}
public void demo() {
System.out.println("This is Overrided method");
}
}
Output will be "This is Override method" and if you comment the demo method like below
public class practice extends Demo1 implements Demo {
public static void main(String[] args ) {
practice p=new practice();
p.demo();
}
/*public void demo() {
System.out.println("This is Overrided method");
}*/
}
Output will be "this is demo10". In first case as class object finds definition of demo in self, it will give preference to this over to parent class.
Demo1 is providing implemetation of demo(). so it will take parent demo() method. Output will be
this is demo10
But then you have implemented again overriding of demo() method in child class practice
so output is now
This is Overrided method
I have two java class files
Hi.java which belongs to second package
package second;
public class Hi {
protected int v=20;
protected void m(){
System.out.println("i am protectTED");
}
}
S.java which belong to first package
package first;
import second.Hi;
interface i1
{
void m();
int a=200;
}
interface i2{
void m1();
int b=100;
}
class S extends Hi implements i1,i2
{
int a=50;
public void m()
{
System.out.println("hi");
}
public void m1()
{
System.out.println("hello");
}
public static void main(String[] args) {
S s=new S();
/*need correction here (i don't know the exact syntax to mention to get
the desired output)
s.m(); //should invoke method m() from class Hi only.
s.m(); //Should invoke method m() from class S only.
*/
//the following statements prints the desired values
s.m1();
System.out.println(s.v);
System.out.println(i1.a);
System.out.println(s.a);
System.out.println(b);
}
}
when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.
How to differentiate the 2 methods for invoking. Is it even possible?
when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.
Correct, because you've overridden it with m in S. Overriding methods is fundamentally different from overriding fields. (And in general, it's best to avoid overriding any fields that are visible to your subclass, as you're doing with a.)
In instance code in S, you can run the inherited m via super: super.m(). But you cannot do that from static code, not even static code in S. You could give yourself a private callSuperM in S:
private void callSuperM() {
super.m();
}
...and then use that in main:
s.callSuperM(); // "i am protectTED"
s.m(); // "hi"
My code:
public class PrivateOverride {
private void f() {
System.out.println("private f()");
}
public static void main(String[] args) {
PrivateOverride po = new derived();
po.f();
}
}
class derived extends PrivateOverride {
public void f() {
System.out.println("public f()");
}
}
Output:
private f()
Why?
Because derived#f() does not override parent's class private f() method.
You could confirm it by adding #Override annotation to f() method in derived class and see that it won't compile.
Extra tips :
To override method f(), it should be inherited from parent's class, i.e. visible in your subclass, which is never the case for private methods.
Additional rules for correct method overriding are summarized in this table.
derived cannot see PrivateOverride's f() because it's private, and hence that is not an overriding, it's definition of a new method. It's always recommended to add the annotation #Override on the overridden method just to avoid such hidden problems.
Method f in PrivateOverride is declared as private. That means that it isn't overridden in derived class.
That's why you should use #Override annotation. In that case it would show you the error.
Because Private method can't be Inherited in subclass so it can't be overridden.
what will be the flow of execution in case of override? What i believe is , when we call a constructor/object of any class, during execution first it call parent constructor and than child. but what will happen in case of over ridding?
lets suppose:
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
public class Test2 {
public static void main(String[] args){
B b = new B();
}
}
Out put of this code is:
In Class b
In Class b
what i don't understand is, why it's printing "In Class be" only, it should be "In class A and, In Class b",
when i remove override method from class b. it give me desired output.
All java methods are virtual. It means the method is called with using actual type of this. So inside of constructor A() {} this is the instance of B, so that is why you've got its method call.
Calling like this printStatus() will call the method from the same class. If you call with super.printStatus() it will envoke method from the super class (class which you have extended).
When you over-ride a method you over-ride it completely. The existence of the original implementation is completely invisible to other classes (except via reflection but that's a big topic of its own and not really relevant). Only your own class can access the original method and that is by calling super.methodName().
Note that your class can call super.methodName() anywhere, not just in the overriding function, although the most usual use for it is in the overriding function if you want the super implementation to run as well as your own.
Constructors are a slightly special case as there are rules about how and why constructors are called in order to make sure that your super-class is fully initialized when you try and use it in the inheriting class.
super is always called whether you write super(); or not.
In the example printStatus() method of Class A will never be called. Since you are creating an instance of class B and there will be method overriding. You can use the following to call the Class A printStatus() method.
public B()
{
super.printStatus();
}
When you override a method, it will override the one that you expect from class A.
Should use super keyword for calling super class method.
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
super.printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
Constructor public B(){ super.printStatus(); } calls Class A print method and constructor public A(){ printStatus(); } calls Class B print method since you've overridden.
But its wrong with overridable method calls in constructors.
Try with like this :
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
super.printStatus();
printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
public class Test2 {
public static void main(String[] args){
B b = new B();
}
}
For better understanding the concepts of Overloading and Overriding just go through this links:
http://en.wikibooks.org/wiki/Java_Programming/Overloading_Methods_and_Constructors
I'm trying to create a game engine in Java that uses the syntax and structure of UnityScript, and i've got most of it figured out at the moment. The only thing i'm struggling with is being able to call functions when instantiating a class from the superclass.
Example:
Object superclass:
public class Object {
public Object(){
Start();
}
public void Start(){
}
}
Gameobject subclass:
public class GameObject extends Object {
public GameObject(){
}
public void Start(){
}
}
The thing i want to happen is that when i create a new gameobject or anything that extends from a gameobject calls the Start() function when instanced, preferably without using the super() statement.
Parent no-argument constructors will be called automatically if you exclude the super statement, so your code will work as-is.
Fix your method names to follow convention.
Have your super class implement a private method that does its general logic and then calls the start() method, possibly your sub class'. Put a call to this private method in the constructor of the super class.
Your superclass
public abstract class SomeObject {
public Object(){
objectStart();
}
private void objectStart(){
// do something general
start();
}
public abstract void start();
}
Gameobject subclass:
public class GameObject extends SomeObject {
public GameObject(){
// implicitly calls super() which will call objectStart() which will call start()
}
#Override
public void start(){
}
}
Now when any subclass of SomeObject gets instantiated, its start() method will get executed.
If you don't want the class to be abstract, just implement a no-op start() method