gpt4 book ai didi

java - 抽象类和 toString() 方法

转载 作者:行者123 更新时间:2023-12-02 06:31:25 25 4
gpt4 key购买 nike

我对如何设置 TestHomework 方法以便在使用 toString() 方法时正确打印感到有点困惑。现在,当我运行 main 方法时,它会打印“null - 0”,但我希望它显示的是“Math - 6”。该程序应该扩展一个抽象类。它应该说明家庭作业有多少页以及什么主题。

public abstract class Homework {

private int pagesToRead;
private String typeHomework;

{
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}

public Homework(int pages, String hw) {

this.pagesToRead = pages;
this.typeHomework = hw;

}

public abstract void createAssignment(int p);

public int getPages() {
return pagesToRead;
}

public void setPagesToRead(int p) {
pagesToRead = p;
}

public String getTypeHomework() {
return typeHomework;
}

public void setTypeHomework(String hw) {
typeHomework = hw;
}

}

public class MyMath extends Homework {

private int pagesRead;
private String typeHomework;

public MyMath(int pages, String hw) {
super(pages,hw);
}

public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}

public String toString() {
return typeHomework + " - " + pagesRead;
}
}

public class TestHomework {

public static void main(String[] args) {
MyMath one = new MyMath(6, "Math");
one.createAssignment(6);
System.out.println(one);
}

}

最佳答案

那是因为您正在定义 2 个属性(其中一个恰好与抽象类之一具有相同的名称)但您没有初始化它们,而是初始化了抽象类的属性。 (因此它们的值始终设置为其类型的默认值)

您需要从 MyMath 类中删除它们,并在您的抽象类中定义 toString 方法:它是其继承类默认使用的方法。

public abstract class Homework {

private int pagesToRead;
private String typeHomework;

// Same code

// Define the toString here
@Override
public String toString() {
return typeHomework + " - " + pagesToRead;
}
}

public class MyMath extends Homework {

// You don't need to define any extra attributes

public MyMath(int pages, String hw) {
super(pages,hw);
}

public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
}


public static void main(String[] args) {
// Calls the constructor of the MyMath class, which in turn
// invokes the constructor of its superclass, the 'Homework' class
MyMath one = new MyMath(6, "Math");
one.createAssignment(6);

// Invokes the toString of the MyMath class. Since it does not have one,
// The toString method of its superclass (Homework) is called.
System.out.println(one);
}

关于java - 抽象类和 toString() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35393447/

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