Discuss / Java / 补充

补充

Topic source

在下面的代码中`p.getScore()`会编译出错,因为变量类型是父类Person,调用的方法只能是在父类中有定义的,子类中特有的方法无法访问。

变量只是实际赋值对象的一个小观测窗口,即使作为变量值的对象有很多方法,但在使用这个变量来调用方法时,只能调用该变量类型“知道”的方法。

class Main{
    public static void main(String[] agrs){
        Person p = new Student("张三", 18, 80);
        System.out.println(p.getScore());
    }
}
class Person{
    protected String name;
    
    protected int age;
    
    public Person(String name, int age){
        this.name = name;
        
        this.age = age;
    }
    
     public String getName(){
     
     return this.name;
      }
}

class Student extends Person{


    protected  int score;
    
    public Student(String name,int age,int score){
        super(name,age);
        this.score = score;
    }
    
    public int getScore(){
        return this.score;
    }
}

  • 1

Reply