首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java类直接实例化而不调用构造函数?

Java类直接实例化而不调用构造函数?
EN

Stack Overflow用户
提问于 2019-03-01 03:53:34
回答 1查看 76关注 0票数 0

刚开始学习Java。

由于某种原因,如果没有类实例化自身的实例,我就无法创建一个类?

我就不能创建一个类并扩展我的当前类吗?如果我试图调用它的内部函数,它就会复制这个函数。

我正在努力学习关于继承的知识,以及如何使代码更加模块化

代码语言:javascript
复制
import java.util.InputMismatchException;
import java.util.Scanner;

public class Character extends ClassAttribute {

    public String classType;
    public int health;
    public Object selection;

    public static void main(String[] args) {
        Character chris = new Character();
        System.out.println("your class is: " + chris.classType);
        System.out.println("your health is: " + chris.health);
    };

    public Character() {

        ClassAttribute choice = new ClassAttribute();
        this.classType = choice.classType;
        this.health = choice.health;

    }
}

public class ClassAttribute {

    public String classType;
    public int health;
    public String choice;

    public void human() {
        this.health = 100;
        this.classType = "Human";

    }

    public void ai() {
        this.health = 110;
        this.classType = "Ai";
    }

    public ClassAttribute() {
        System.out.println("Choose a class type (Human || Ai)");
        Scanner readClassChoice = new Scanner(System.in);

        while (!"Ai".equals(this.choice) && !"Human".equals(this.choice)) {
            try {
                this.choice = readClassChoice.nextLine();
            } catch (InputMismatchException e) {
                System.out.println("Please enter a valid class (Ai || Human)");
                readClassChoice.next();
            }
            ;
        }

        if ("Ai".equals(this.choice)) {
            ai();
        } else {
            human();
        }

    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-01 04:13:31

执行解释:

我猜您对字符和ClassAttribute类中的执行顺序感到困惑。在扩展类时,您必须记住的一件事是,类的构造函数将调用其超类或父类的零参数构造函数,等等,直到到达第一个祖先。

因此,在代码中,您在主方法中创建一个字符实例,这将触发字符构造函数,但是在创建ClassAtribute实例之前,字符构造函数将调用ClassAttribute构造函数,因此执行扫描程序代码。

一旦完成,它将返回到字符构造函数并创建一个ClassAttribute实例,该实例将再次执行构造函数,但是对于这个局部变量实例,您的扫描程序代码将再次执行。

因此,您有两个ClassAtribute类,一个在main创建,一个在字符构造函数中创建,两个都执行ClassAtribute构造函数。

由于继承,您不必在构造函数处创建父实例来访问父方法,只需使用thissuper关键字访问父方法即可。

不好的继承示例,这也不是一个很好的继承示例,当您学习java时,您会发现两个基本的关系:组合(有a)和继承( is )。如果您从ClassAtribute扩展字符,您的意思是“字符是一个ClassAtribute”,这似乎是令人困惑和错误的。更自然的说法是“性格具有健康属性”。

一个更好的示例更合适的示例是“字符具有属性健康”。然后"A ArtificialIntelligence是一个字符“和”A Human is一个字符“可以翻译成:

代码语言:javascript
复制
class Character {
  String health;
}

class ArtificialIntelligence extends Character { }

class Human  extends Character { }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54937704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档