2015-08-14 60 views
-4

1:继承代码的可重用

class arbitrary { 
    void print() { 
     System.out.println("Hello Inheritance"); 
    } 
} 
public class inheritance extends arbitrary { 
    public static void main(String args[]) { 
     arbitrary ar = new arbitrary(); 
     ar.print(); 
    } 
} 

输出:你好继承

2:

class arbitrary { 
    void print() { 
     System.out.println("Hello Inheritance"); 
    } 
} 
public class inheritance extends arbitrary { 
    public static void main(String args[]) { 
     inheritance in = new inheritance(); in .print(); 
    } 
} 

输出:你好继承

3:

class arbitrary { 
    void print() { 
     System.out.println("Hello Inheritance"); 
    } 
} 
public class inheritance { 
    public static void main(String args[]) { 
     arbitrary ar = new arbitrary(); 
     ar.print(); 
    } 
} 

输出:你好继承

4:

class arbitrary { 
    void print() { 
     System.out.println("Hello Inheritance"); 
    } 
} 
public class inheritance { 
    public static void main(String args[]) { 
     inheritance in = new inheritance(); in .print(); 
    } 
} 

输出:错误

第1个和第2个程序使用继承和可重用性的概念,但在基类(即,继承)不扩展超类(即任意)仍然运行成功。 那么没有扩展如何重用超类的代码?任何人都可以帮助我弄清楚,第三方程序如何在不使用继承和可重用性的情况下成功运行。

+0

Eeew。至少缩进你的代码。 – Mena

+0

你能直接缩进你的代码吗? – 9Deuce

+0

目前还不清楚你在问什么。第四个程序不会编译,因为您正尝试在继承对象中调用一个名为print()的方法,该方法没有定义该方法。所有其他示例在正在创建的对象上定义该方法。第三和第四个例子与继承无关。 – David

回答

2

您的第一个和第三个程序实际上是相同的。

Inheritance类的扩展并不重要,因为你并没有真正使用它。您的main仅使用Arbitrary类,并且由于Arbitrary类具有print方法,因此它会成功并打印该消息。

你的第二个例子工作,因为Inheritance延伸Arbitrary,并且您正在使用Inheritance类为您的对象。由于它延伸到Arbitrary,它具有所有Arbitrary的方法,因此具有print并且将成功打印。

但是你的第四个示例使用了一个Inheritance对象。但是,尽管它的名称不是Arbitrary,并且除main之外没有其他方法,这意味着它也没有print方法。因此错误。

你的困惑或许源于:

  • 你的信念,即方案1展示了继承。它并不真的。您没有使用扩展类,因此没有使用继承。
  • 你相信3和4具有相同的逻辑。他们不。你的第三个使用的Arbitrary类有print方法,但你的第4个使用Inheritance类,它没有print方法。
0

第三个程序的工作原理是因为您正在创建arbitrary类的实例,因此可以通过调用arbitrary对象来使用它的方法。

第四个并不是因为零类连接到arbitrary类。该方法在inheritance类的范围内不存在。

0

在第4个代码中,inheritance类没有任何方法,称为print,所以它给出错误。

在第三个代码中,arbitrary对象有一个名为print的方法,所以它运行成功。

在第二代码中,inheritance类继承了arbitrary类,所以它有一个叫做print的方法。