Interface and Abstract class ad method overriding

2019-01-28 06:33发布

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?

3条回答
贼婆χ
2楼-- · 2019-01-28 07:08

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.
}
查看更多
对你真心纯属浪费
3楼-- · 2019-01-28 07:16

The answer is short: Both.....

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

查看更多
贼婆χ
4楼-- · 2019-01-28 07:20

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.

查看更多
登录 后发表回答