interface CarePet {
public void feed();
public void enjoy();
}class Student implements CarePet {
String name;

Student(String name) {
this.name =  name;
}

public void feed() {
System.out.println("学生喂养宠物");
}

public void enjoy() {
System.out.println("宠物很enjoy~~");
}
}class Farmer extends Student implements CarePet {
Farmer(String n) {
super(n);
}

public void feed() {
System.out.println("农民喂养宠物");
}

public void enjoy() {
System.out.println("宠物同时也是食物");
}
}public class Tinterface {
public static void main(String args[]) {
CarePet c1 = new Student("seven");
System.out.println("一个叫" + c1.name + "的");
c1.feed();
c1.enjoy();
System.out.println("==========================================================================");
CarePet c2 = new Farmer("jack");
System.out.println("一个叫" + c2.name + "的");
c2.feed();
c2.enjoy();
}
}E:\java\interface>javac Tinterface.java
Tinterface.java:39: 找不到符号
符号: 变量 name
位置: 接口 CarePet
                System.out.println("一个叫" + c1.name + "的");
                                             ^
Tinterface.java:44: 找不到符号
符号: 变量 name
位置: 接口 CarePet
                System.out.println("一个叫" + c2.name + "的");
                                             ^
2 错误

解决方案 »

  1.   

    CarePet 没有定义name
    可以试试强制转换为Student类型.
      

  2.   

    显然不对啊,c1和c2是CarePet类型的,但CarePet没有这个变量啊!
      

  3.   

    我改成这样了,不知道是不是你想表达的意思!
    interface CarePet {
        public String getName();
        public void feed();
        public void enjoy();
    }class Student implements CarePet {
        String name;
        
        Student(String name) {
            this.name =  name;
        }
        
        public void feed() {
            System.out.println("学生喂养宠物");
        }
        
        public void enjoy() {
            System.out.println("宠物很enjoy~~");
        }    public String getName() {
          return name;
        }
    }class Farmer extends Student implements CarePet {
        Farmer(String n) {
            super(n);
        }
        
        public void feed() {
            System.out.println("农民喂养宠物");
        }
        
        public void enjoy() {
            System.out.println("宠物同时也是食物");
        }
    }public class Tinterface {
        public static void main(String args[]) {
            CarePet c1 = new Student("seven");
            System.out.println("一个叫" + c1.getName() + "的");
            c1.feed();
            c1.enjoy();
            System.out.println("==========================================================================");
            CarePet c2 = new Farmer("jack");
            System.out.println("一个叫" + c2.getName() + "的");
            c2.feed();
            c2.enjoy();
        }
    }