java - 如何让驱动类继承超类的某些属性?
问题描述
我试图让我的驱动程序类从两个不同的类继承信息。我必须使用公式 className objectName = new className(input parameters) 来实例化其中一个类。但我不断收到符号无法识别的错误。
我不确定如何解决这个问题。我尝试创建一个导入语句,但其他两个类是同一个包的一部分。我也尝试过使用 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 tricker = new Corgi(); 继承 Corgi 的信息。陈述。但我不断收到错误:
Main.java:6: 错误:找不到符号 Corgi tricker = new Corgi("Hunting", "Shiba", "Simon", 30, 7);
^ 符号:类 Corgi 位置:类 Main
解决方案
- 在您
Corgi class
需要从中删除变量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.然后您必须添加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.
推荐阅读
- elasticsearch - 如何获取 Kibana 和 Elasticsearch 使用的指标原始数据规范?
- python - 插入或删除条目时如何自动更新列表框小部件?
- regex - 正则表达式:使用正则表达式匹配字符串的第 5 到第 12 个字符
- node.js - 如何处理异步/等待函数中的错误?
- java - 尝试使用谓词、标准和规范为存储库接口编写 Junit
- ios - 通过 ContextMenu 呈现的工作表在第一次尝试时丢失了它的数据
- php - 如何在 Laravel Eloquent 上过滤相关模型
- openssl - PDF格式的白俄罗斯数字签名验证
- java - 对给定整数的数字进行排序,不带“0”
- sql - 在一个 SQL 查询中组合多个总和