Java 继承工具
我从一本书中学习Java。我已经完成了《继承》这一集,但我不理解《用户界面》这一集中的示例程序:Java 继承工具,java,inheritance,Java,Inheritance,我从一本书中学习Java。我已经完成了《继承》这一集,但我不理解《用户界面》这一集中的示例程序: public class AWTApp extends Frame { ... public AWTApp(String caption) { super(caption); setLayout(new GridLayout(PANELS_NO, 1)); for(int i=0;i<PANELS_NO;i++) {
public class AWTApp extends Frame {
...
public AWTApp(String caption)
{
super(caption);
setLayout(new GridLayout(PANELS_NO, 1));
for(int i=0;i<PANELS_NO;i++)
{
panels[i]=new Panel();
add(panels[i]);
}
label_test(panels[0]);
...
}
}
公共类AWTApp扩展框架{
...
公共AWTApp(字符串标题)
{
超级(标题);
setLayout(新网格布局(面板编号1));
对于(int i=0;i公共类AWTApp扩展帧
这意味着AWTApp是一个
帧
所以当你打电话的时候
public AWTApp(String caption)
{
super(caption); // here you are calling super constructor the frame constructor and creating the frame
this.setLayout(new GridLayout(PANELS_NO, 1)); // cause you are a frame you can call with this parents public protected (and package if they are in the same package)
this.add(..);
}
}
这里有一些解释
首先,一些代码:
public class Parent{
public void doThing(){
System.out.println("I did a thing!");
}
}
public class Child extends Parent{
public void doAnotherThing(){
System.out.println("I did another thing!");
}
}
public class MainClass{
public static void main(String[] args){
Parent p = new Parent();
Child c = new Child();
p.doThing();
c.doThing(); // This is correct because c is a Parent!
c.doAnotherThing(); // This is correct, because c is also a child.
}
}
Child
继承所有的Parent
方法,因为Child
只是Parent
的一个扩展。在您的程序上下文中,这意味着AWTApp可以调用Frame的所有方法,因为它是一个框架,因此可以执行框架可以执行的任何操作,以及它自己的方法。AWTApp
是一个框架Frame
。调用add()时
在构造函数中,您在this
上调用它,这是对类型为AWTApp
的对象的引用。谢谢!我明天会努力更好地理解它。这很难理解。您知道我在哪里可以找到继承练习吗?我总是会找到包含我没有学过的内容的非常难的练习然而