面向对象的三大特征:继承、封装、多态
继承
继承让我们更加容易实现类的扩展。 比如,我们定义了人类,再定义Boy类就只需要扩展人类即可。实现了代码的重用,不用再重新发明轮子(don’t reinvent wheels)。
知识点
- 父类也称基类,超类
- Java中类没有多继承只有单继承,接口有多继承
- 子类继承父类,可以得到父类的全部属性和方法(除父类的构造方法),但不是都可以访问
可以使用Ctrl+T很方便的查看类的继承层次结构
extend关键字
从英文字面意思理解,extends的意思是“扩展”。子类是父类的扩展。
instanceof关键字
instanceof是二元运算符,左边是对象,右边是类;当对象是右面类或子类所创建对象时,返回true;否则,返回false。
package OOprogress;
/**
* 测试继承extend和instanceof
* @author DELL
*
*/
public class testExtendAndInstanceof {
public static void main(String[] argd) {
studentSimple stu = new studentSimple();
stu.name = "杨致远";
stu.height = 180;
stu.rest();
studentSimple sut1 = new studentSimple();
studentSimple sut2 = new studentSimple("希希", 6, "挖掘机专业");
//test instanceof
System.out.println(stu instanceof studentSimple);
System.out.println(stu instanceof person);
System.out.println(stu instanceof Object);
System.out.println(new person() instanceof studentSimple);
}
}
class person{
String name;
int height;
String major;
public void rest() {
System.out.println("休息一会 ! ");
}
}
class Student{
String name;
int height;
String major;
public void study() {
System.out.println("学习两小时 !");
}
public void rest() {
System.out.println("休息一会 ! ");
}
}
//上述Student类含有很多person类中的属性,可以用继承来简化
class studentSimple extends person {
String major;
//在加了自定义的构造器后,默认构造器就会被屏蔽,需要手动加上,不然缺省构造函数无法调用
public studentSimple(String name, int height, String major) {
this.name = name;
this.height = height;
this.major = major;
}
//手动加上默认构造器
public studentSimple() {
}
public void study() {
System.out.println("学习两小时 !");
}
}
选中派生类摁Ctrl+T可以看继承结构
方法的重写override
子类通过重写父类的方法,可以用自身的行为替换父类的行为。方法的重写是实现多态的必要条件。
方法的重写需要符合下面的三个要点:
1.“==”: 方法名、形参列表相同。
2.“≤”:返回值类型和声明异常类型,子类小于等于父类。
3.“≥”: 访问权限,子类大于等于父类。
package OOprogress;
/*
* 测试重写(overload)/覆盖
*/
import OOprogress.testExtendAndInstanceof;
public class testOverload {
public static void main(String[] argd) {
Horse h = new Horse();
h.run();
}
}
class Vehicle{
public void run() {
System.out.println("跑...");
}
public void stop() {
System.out.println("停止!!!");
}
public person whoIsPassenger() {
return new person();
}
}
class Horse extends Vehicle{
//覆盖超类的run方法
public void run() {
System.out.println("马蹄翻飞,嘚嘚嘚...");
}
//studentSimple->person->Object
//重写超类的run方法
/*error 大于
public Object whoIsPassenger() {
return new Object();
}
*/
/*right 等于
public person whoIsPassenger() {
return new person();
}
*/
//返回值的类型应该小于等于父类的类型 小于
public studentSimple whoIsPassenger() {
return new studentSimple();
}
}
s