Interface and Abstract class ad method overriding

房东的猫 提交于 2019-12-29 08:45:30

问题


Here is the code:

interface hi
{
    public void meth1();
}
abstract class Hullo
{
    public abstract void meth1();
}
public class Hello extends Hullo implements hi
{
    public void meth1(){}
}

Question:The code compiles and everything. I wanted to know the meth1() in class Hello is overriding which meth1()? The ont in the interface or the one in the abstract class and why?


回答1:


The answer is short: Both.....

In fact, to be correct: You are overriding none of them, you are implementing them both, with one method.




回答2:


Generally we override a existing method which already has some definition. I mean we are adding a extra bit of feature in child class compared to super class. Since both methods are abstract, so we can say that we implementing the unimplemented method.

You can take the reference of creating threads in Java where we prefer to implement Runnable interface compared to extending Thread class.




回答3:


Absolutely correct question.

Here both the interface and abstract class have same method.

You have one class name is hello and extends abstract class and implement interface its true and you override meth1 method on hello class its fine and its compile correctly and not given any error but her you can't identify which class method is override like abstract class or interface.

This is runtime polymorphism you can't create object of abstract class and interface but you can create reference variable of that. Here solution is you can't identify that on compile time its actual override at runtime.

    interface hi
{
    public void meth1();
}
abstract class Hullo
{
    public abstract void meth1();
}
public class Hello extends Hullo implements hi
{
    public void meth1(){
        System.out.println("hello");
    }
        hi h= new Hello();
        h.meth1();//its means interface method is override. and its decide when we call method.
        hullo hu= new Hello();
        hu.meth1();//its means abstract class method is override.
}


来源:https://stackoverflow.com/questions/11434137/interface-and-abstract-class-ad-method-overriding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!