面向对象三大特性:封装、继承、多态封装
对外隐藏其内部实现方式,可以在不影响外部调用的情况下修改其内部的实现方式继承
import java.text.MessageFormat;
public class Person {
private String name;
private Integer age;
Person() {}
Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String introduceSelf() {
return MessageFormat.format("我叫{0},今年{1}岁", name, age);
}
}
import java.text.MessageFormat;
public class Student extends Person {
Student() {}
Student(String name, Integer age) {
super(name, age);
}
@Override
public String introduceSelf() {
return MessageFormat.format("我是一个学生,{0}", super.introduceSelf());
}
public String study() {
return "我正在听课中,有事微信联系";
}
}
import java.text.MessageFormat;
public class Teacher extends Person {
Teacher() {}
Teacher(String name, Integer age) {
super(name, age);
}
@Override
public String introduceSelf() {
return MessageFormat.format("我是一个老师,{0}", super.introduceSelf());
}
public String lecture() {
return "我正在给学生上课,有事微信联系";
}
}
import java.text.MessageFormat;
public class Demo {
public static void main(String[] args) {
// Person person = new Student("张三", 16);
// // 由于子类发生了向上转型,所以会失去使用父类中所没有方法的权力
// person.study();
Student student = new Student("张三", 16);
// 我是一个学生,我叫张三,今年16岁,我正在听课中,有事微信联系
System.out.println(MessageFormat.format("{0},{1}",student.introduceSelf(),student.study()));
//
Teacher teacher = new Teacher("李四", 30);
// 我是一个老师,我叫李四,今年30岁,我正在给学生上课,有事微信联系
System.out.println(MessageFormat.format("{0},{1}",teacher.introduceSelf(),teacher.lecture()));
}
}
总结: Person类是对学生类和老师类中相同属性、方法的抽取,实现代码的复用
- 1、父类中的私有属性和方法不能被子类继承
- 2、子类可以拓展父类中的属性、方法
- 3、如果父类的方法不能满足子类的需求,子类可以对其重写
- 描述:同一个事件发生在不同的对象上会产生不同的结果
- 实现必要条件:继承、重写、父类引用指向子类对象
public class Demo {
public static void main(String[] args) {
Person student = new Student("张三", 16);
// 我是一个学生,我叫张三,今年16岁
System.out.println(student.introduceSelf());
//
Person teacher = new Teacher("李四", 30);
// 我是一个老师,我叫李四,今年30岁
System.out.println(teacher.introduceSelf());
}
}
【重写】子类对父类中public修饰的方法的实现过程进行重新编写, 返回值和形参都不能改变 【重载】 在一个类里面,方法名字相同,而参数不同,返回类型可以相同也可以不同



