继承java解释

继承java解释,java,inheritance,Java,Inheritance,有人能给我解释一下这个程序的执行情况吗?? 我知道扩展关键字的作用。但我仍然无法弄清楚结果是什么,为什么 public class Maryland extends State { Maryland() { /* null constructor */ } public void printMe() { System.out.println("Read it."); } public static void main(String[] args) { Re

有人能给我解释一下这个程序的执行情况吗?? 我知道
扩展
关键字的作用。但我仍然无法弄清楚结果是什么,为什么

public class Maryland extends State {
    Maryland() { /* null constructor */ }
    public void printMe() { System.out.println("Read it."); }
    public static void main(String[] args) {
        Region mid = new State();
        State md = new Maryland();
        Object obj = new Place();
        Place usa = new Region();
        md.printMe();
        mid.printMe();
        ((Place) obj).printMe();
        obj = md;
        ((Maryland) obj).printMe();
        obj = usa;
        ((Place) obj).printMe();
        usa = md;
        ((Place) usa).printMe();
        }
    }

class State extends Region {
    State() { /* null constructor */ }
    public void printMe() { System.out.println("Ship it."); }
    }

    class Region extends Place {
    Region() { /* null constructor */ }
    public void printMe() { System.out.println("Box it."); }
    }

    class Place extends Object {
    Place() { /* null constructor */ }
    public void printMe() { System.out.println("Buy it."); }
}

运行它,您将看到结果。你还需要什么

Read it.
Ship it.
Buy it.
Read it.
Box it.
Read it.

需要关于动态多态性和继承的知识。程序没有复杂性。
在调试模式下执行程序,并逐行检查执行情况。您将理解流程。

请记住这条规则

方法重写
继承
一起使用时,将调用该
类的
方法
最特定版本

例如:

Maryland
类有
printMe()
方法,该方法打印“读取它”。

State
类具有打印“Ship it”的
printMe()
方法

现在它是
方法重写
以及
继承
类多态性的一个例子。

State md = new Maryland();
State
Maryland
类的超级类,所以它是这样的

Object Reference Variable of Super class  md  =  Object of Subclass ;
这是编译器的一个典型行为,只有当方法存在于对象引用变量类中时,才调用它,因为除非方法存在于超类中,否则它不会知道任何关于它的信息,即使它存在于它的子类中

所以当我们这样做的时候

md.printMe()


然后根据“将调用该类方法的最特定版本”的规则,将调用Maryland类的
printMe()
方法,因此它将打印阅读它。

搜索,您将发现:非常长且不可读的代码段,没有明显的努力去理解这个问题……每个Java程序都必须从
main()
开始。这段代码的第一行是做什么的?下一个呢?按照这个模式来了解整个程序的功能。如果有一行你很难理解,请随时回来具体询问。@Code Guru:程序以main()开头。它在同一个程序中使用了多个类,其中
main()
函数位于
Maryland()
类中。@xan你知道我不是OP吗?我的评论是对OP的一个提示,告诉他/她如何自己解决这个问题。此外,你可以添加跟踪(即使是一个简单的
System.out.println(someMessage)
,以了解代码中发生了什么。或者使用调试器查看代码是如何移动的。好的。那么这些语句呢?
obj=md;((马里兰)obj.printMe();
@user188995类始终隐式扩展对象类…您正在显式转换Maryland对象,因此再次遵循规则和printMe()调用了Maryland类的方法。@KumarVivekMitra:您是指方法重写。重载是指当您具有相同的方法名称和不同的参数集时。@Matt yup…我是指方法重写,其中方法的参数具有相同的数字,具有相同的名称和相同的返回类型,但是的,访问修饰符可以更宽从超级班到次级班…是的,谢谢马特,这是一个打字错误…我改进了它…再次感谢