gpt4 book ai didi

java - 在 main 方法的类中扩展 Frame 类

转载 作者:行者123 更新时间:2023-11-30 06:26:50 26 4
gpt4 key购买 nike

今天,当我阅读我的讲义时,我不明白 extends 在这种情况下的目的是什么。考虑这段代码:

import java.net.*;    
import java.awt.*;

public class QueenApl extends Frame{ // Why extends??
Image card;

public static void main(String[] args){
QueenApl f = new QueenApl();
f.show();
}

public QueenApl(){
setSize(400,400);
try{
URL u = new URL("file:/c:/windows/desktop/carn4.jpg");
card=getToolkit().getImage(u); //Why getToolkit can be used directly?
}catch(MalformedURLException e){
System.out.println("Error in URL!"); System.exit(1);
}
}

public void paint(Graphics g){
g.drawImage(card,120,50,this);
}
}
  1. 为什么main方法类扩展了Frame类?为什么 Frame 不是在 main 方法中创建的,或者不是作为类 QueenApl 的实例变量创建的?像这样:

    Frame someobj = new Frame(argument or none);
  2. 为什么getToolkit()可以不在前面追加classname.直接使用?是不是因为这个方法在Frame类中,而且main方法类继承了Frame,所以我们可以直接使用这个方法?

最佳答案

extends 是代表继承的关键字。

Why the main method class is extends to Frame ? Why don't Frame being created inside the main method or as the instance variable of class QueenApl Frame something = new Frame(argument or none) ?

不同之处在于,当您扩展 Frame 类时,您会在您的类中获取它的方法。即,您可以覆盖 QueenApl 类中框架类中声明的方法。

为了更好地理解这里有一个臭名昭著的 Animal 示例:

class Animal {
public void eat(){
//animal eat
}
class Dog extends Animal {
@override
public void eat(){
//dog specific eat
}
}
}

请注意,您已经覆盖了 Dog 类中的 eat 方法以实现特定于狗的 eat 操作。

2.)By the way why getToolkit() can be used directly without append the classname. in front of it ? Is it because this method is in the class Frame and since the main method class inherit Frame , we can use the method directly ?

那是因为您的 getToolKit() 方法是从您的 Frame 类 继承的,因此您不需要使用实例调用它。

关于java - 在 main 方法的类中扩展 Frame 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13937443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com