在OOP的术语中,我们把Student称为超类(super class),父类(parent class),基类(base class),把Student2称为子类(subclass),扩展类(extended class)。
Student stu=new Student();
stu.setName("admin");
System.out.println(stu.getName());
Student2 stu2=new Student2();
stu2.setName("admin");
stu2.setAge(123);
stu2.setClas("Iot1903");
stu2.setId(1001);
System.out.println(stu2.getName()+" "+stu2.getAge()+" "+stu2.getclas()+" "+stu2.getId());
//继承
class Student{
private String name;
private int age;
private String clas;
public String getName(){return this.name;}
public void setName(String name){this.name=name;}
public int getAge(){return this.age;}
public void setAge(int age){this.age=age;}
public String getclas(){return this.clas;}
public void setClas(String clas){this.clas=clas;}
}
class Student2 extends Student{
//继承了Student里所有的功能,我们只需要添加新的功能即可
private int id;
public int getId(){return this.id;}
public void setId(int id){this.id=id;}
}
{/tabs-pane}
{tabs-pane label="private效果"}
{/tabs-pane}
{tabs-pane label="protected"}
继承有个特点,就是子类无法访问父类的Student字段或者private方法。例如,Student2类就无法访问Student类的name和age字,这使得继承的作用被削弱了。为了让子类可以访问父类的字段,我们需要把private改为protected。用protected修饰的字段可以被子类访问:
class Student {
protected String name;
protected int age;
}
class Student2 extends Student {
public String hello() {
return "Hello, " + name; // OK!
}
}
因此,protected关键字可以把字段和方法的访问权限控制在继承树内部,一个protected字段和方法可以被其子类,以及子类的子类所访问。
{/tabs-pane}
{tabs-pane label="super"}
super关键字表示父类(超类)。子类引用父类的字段时,可以用super.fieldName。
class Student2 extends Student {
public String hello() {
return "Hello, " + super.name;
}
}
//这里使用super.name,或者this.name,或者name,效果都是一样的。编译器会自动定位到父类的name字段。
在某些时候,就必须使用super
public class Main {
public static void main(String[] args) {
Student2 s = new Student2("lq", 12, 89);
}
}
class Student {
protected String name;
protected int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Student2 extends Student {
protected int score;
public Student(String name, int age, int score) {
//因为在Java中,任何class的构造方法,第一行语句必须是调用父类的构造方法。如果没有明确地调用父类的构造方法,编译器会帮我们自动加一句super();
//super();因为在Student类中并没有无参数的构造方法,所以这句话会报错 应改为下列中:
super(name,age);
this.score = score;
}
}
{/tabs-pane}
{tabs-pane label="final"}
final不允许子类覆写父类的方法
final修饰的类不能被继承 final class Student{} 不能被继承
final修饰的字段在初始化之后不能被修改,
public final String name="我不能被修改了";
可以在构造方法中初始化字段
保证实例一旦创建,其final字段就不可更改
//类不能被继承
final class Student {
protected String name;
}
//方法不能被子类覆写
class Student {
protected String name;
public final String hello() {
return "Hello, " + name;
}
}
Student extends Student {
// compile error: 不允许覆写
@Override
public String hello() {
}
}
class Student {//字段
public final String name = "Unamed";
}
//字段重新赋值
Student p = new Student();
p.name = "New Name"; // compile error!
{/tabs-pane}
本文共 635 个字数,平均阅读时长 ≈ 2分钟
评论