示例:
父类为public子类却为protected,缩小了权限,报错
package com.extend_override_test04;
public class Person {
private String name;//姓名
private int age;//年龄
public Person(String name, int age) {//构造器
this.name = name;
this.age = age;
}
//封装
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String say()//返回属性
{
return "大家好!我的名字是:"+name+"我今年"+age+"岁";
}
public void prift()//打印返回的属性
{
System.out.println(say());
}
}
public class Studnt extends Person {
private int id;//编号
private double score;//分数
public Studnt(String name, int age, int id, double score) {//构造器
super(name, age);
this.id = id;
this.score = score;
}
//封装
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String say()//返回属性
{
//say方法重写了,要返回父类的这时可用super关键字。
return super.say()+"id为:"+id+"分数为:"+score;
}
public void prift()
{
System.out.println(say());
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person("xiaomei",18);
person.prift();
Studnt xiaoming = new Studnt("xiaoming", 17, 6, 78);
xiaoming.prift();
}
}