gpt4 book ai didi

java - 如何让驱动类继承父类(super class)的某些属性?

转载 作者:行者123 更新时间:2023-11-30 05:28:18 24 4
gpt4 key购买 nike

我试图让我的驱动程序类继承两个不同类的信息。我必须使用公式 className objectName = new className(输入参数) 来实例化其中一个类。但我不断收到符号无法识别的错误。

我不知道如何解决这个问题。我尝试创建一个 import 语句,但其他两个类是同一包的一部分。我也尝试过使用 extends 关键字,但也没有运气

public class Corgi extends Dog {

// additional class variables
private static int weight;
private static int age;

// constructor
public Corgi(String type, String breed, String name, int pounds, int years) {

// invoke Dog class (super class) constructor
super(type, breed, name);
weight = pounds;
age = years;
}

// mutator methods
public static int setWeight(int pounds){
weight = pounds;
return pounds;

}

public static int setAge(int years){
age = years;
return years;

}

// override toString() method to include additional dog information
@Override
public String toString() {
return (super.toString() + "\nThe Corgi is " + age +
" years old and weighs " + weight + " pounds.");
}

}
public class Dog {

// class variables
private static String type;
private static String breed;
private static String name;
private static String topTrick;

// constructor
public Dog(){
type = "none";
breed = "none";
name = "none";


}

// methods
public static String setTopTrick(String trick){
topTrick = trick;
return trick;


}

// method used to print Dog information
public String toString() {
String temp = "\nDOG DATA\n" + name + " is a " + breed +
", a " + type + " dog. \nThe top trick is : " +
topTrick + ".";
return temp;
}

}
public class Main 
{
public static void main(String[] args) {

Corgi tricker = new Corgi();

tricker.setTopTrick("Backflip");

System.out.println(tricker);
}
}

我希望能够让主类继承 Corgi 的信息,并使用 Corgi tricker = new Corgi();陈述。但我不断收到错误:

Main.java:6: error: cannot find symbol Corgi tricker = new Corgi("Hunting", "Shiba", "Simon", 30, 7);
^ symbol: class Corgi location: class Main

最佳答案

  1. 在您的 Corgi 类 中,您需要从 super() 中删除变量
 public Corgi(String type, String breed, String name, int pounds, int years) {

// invoke Dog class (super class) constructor
super();
weight = pounds;
age = years;
}

2.然后你必须在“Main class”中的Corgi();中添加值

public static void main(String[] args) {
Corgi tricker = new Corgi("puppy", "Husky", "Alex", 15, 1);

tricker.setTopTrick("Backflip");

System.out.println(tricker);

}

输出-:

DOG DATA
none is a none, a none dog.
The top trick is : Backflip.
The Corgi is 1 years old and weighs 15 pounds.

关于java - 如何让驱动类继承父类(super class)的某些属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58089707/

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