H5W3
当前位置:H5W3 > 其他技术问题 > 正文

java类实现interface以后如何调用

如题,以下代码运行报错,应该这么运行起来呢?

//TestInterface.java

public interface Singer{
    public void sing();
    public void dance();
}

public interface Women{
    public void cook();
    public void care();
}

class Student implements Singer {
    private String name;
    Student(String _name) {
        this.name = _name;
    }
    
    public void sing() {
        System.out.println(this.name + " is singing!");
    }
    
    public void dance() {
        System.out.println(this.name + " is dancing!");
    }
}

class Teacher implements Women, Singer {
    private String name;
    
    Teacher(String _name) {
        this.name = _name;
    }
    
    public void sing() {
        System.out.println(this.name + " is singing!");
    }
    
    public void dance() {
        System.out.println(this.name + " is dancing!");
    }
    
    public void cook() {
        System.out.println(this.name + " is cooking!");
    }
    
    public void care() {
        System.out.println(this.name + " is caring!");
    }
}

public class TestInterface {
    public static void main(String args[]) {
        Student s = new Student("li");
        s.sing();
        s.dance();
        
        Teacher t = new Teacher("wang");
        t.sing();
        t.dance();
        t.cook();
        t.care();
    }
}

运行结果(java 13,不用javac编译)
image.png

回答:

interface 前的public修饰符去掉。
一个.java文件中只能有一个public修饰的同名class、interface或enum

本文地址:H5W3 » java类实现interface以后如何调用

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址