首页 > 解决方案 > 如何让驱动类继承超类的某些属性?

问题描述

我试图让我的驱动程序类从两个不同的类继承信息。我必须使用公式 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

标签: java

解决方案


  1. 在您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.

推荐阅读