【问题标题】:Inheritance java explanation继承java解释
【发布时间】:2012-08-29 17:26:26
【问题描述】:

谁能解释一下这个程序的执行? 我知道extends 关键字的作用。但是我仍然无法弄清楚结果是什么以及为什么??

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."); }
}

【问题讨论】:

  • 非常长且不可读的代码 sn-p,没有明显的努力来理解问题......
  • 每个 Java 程序都必须从 main() 开始。这段代码的第一行是做什么的?下一个呢?按照这个模式来弄清楚整个程序做了什么。如果您有难以理解的特定行,请随时回来具体询问。
  • @Code-Guru:程序以main()开头。它在同一程序中使用多个类,其中main() 函数位于Maryland() 类中。
  • @xan 你知道我不是 OP,对吧?我的评论是对 OP 关于如何自己解决问题的提示。

标签: java inheritance


【解决方案1】:

运行它,你会看到结果。你还需要什么?

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

【讨论】:

  • 另外,您可以添加跟踪(即使是天真的System.out.println(someMessage) 也可以知道代码中发生了什么。或者使用调试器来查看代码是如何移动的。
【解决方案2】:

记住这条规则…………

Method OverRiddinginheritance 一起使用时,将调用methodMost Specific version,用于class

例如:

Maryland 类有 printMe() 方法打印 "Read it."

State 类有 printMe() 方法打印 "Ship it."

现在是Method Overridding 以及inheritanceClass Polymorphism. 的示例

State md = new Maryland();

StateMaryland 类的超类,所以它是这样的..

Object Reference Variable of Super class  md  =  Object of Subclass ;

它是编译器的典型行为,只有当方法存在于对象引用变量类中时,才会调用它,导致直到并且除非该方法存在于超类中,否则它不会知道任何关于它的信息即使它在它的子类中......

所以当我们这样做时......

md.printMe();

然后根据“将调用该类的方法的最具体版本”的规则,将调用马里兰类的printMe()方法,因此打印Read it. p>

【讨论】:

  • 好的。那么这些陈述呢? obj = md; ((Maryland) obj).printMe();
  • @user188995 一个类总是会隐式扩展 Object 类...您正在对 Maryland 对象进行显式转换,因此再次遵循规则并调用 Maryland 类的 printMe() 方法。
  • @KumarVivekMitra :你的意思是方法覆盖。重载是指您具有相同的方法名称和不同的参数集。
  • @Matt yup ....我的意思是方法覆盖,其中方法的参数具有相同的数字,具有相同的名称和相同的返回类型,但是是的,访问修饰符可以更广泛地从超类移动到子类......是的,谢谢马特,这是一个错字......我改进了它......再次感谢
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多