java学习笔记(高琪版)
面向对象OOP
抽象类
抽象类必须要被继承才有意义,他的结构能给子类一个模板,限制子类的设计。
注意:
只能定义抽象方法(类也要被定义为抽象类)
only public, protected, private, static, final, transient & volatile are permitted
抽象类不能被实例化,只能定义子类
Car mycar1 = new Car(); 报错:Cannot instantiate the type Car
继承抽象类的子类必须重写父类中的抽象方法
定义Car抽象类,并且Benze和BMW为子类
package cn.lyr.oop.polymorphismAbustact;
public abstract class Car {
String name;
public abstract void run();
public abstract void maxSpeed();
public void show(){
System.out.println(name);
}
public void star(){
System.out.println("启动啦!");
}
}
class Benze extends Car {
public void run(){
System.out.println("run benze");
}
public void maxSpeed(){
System.out.println("maxSpeed is 290miles per hour");
}
}
class BMW extends Car{
public void run(){
System.out.println("run bmw");
}
public void maxSpeed(){
System.out.println("maxSpeed is 270 miles per hour");
}
}
测试类
package cn.lyr.oop.polymorphismAbustact;
public class test01 {
public static void main(String[]args){
//Car mycar1 = new Car(); 报错:Cannot instantiate the type Car
Car mycar2 = new Benze();
mycar2.name = "京A00001";
mycar2.show();
mycar2.star();
mycar2.run();
mycar2.maxSpeed();
}
}
println:
京A00001
启动啦!
run benze
maxSpeed is 290miles per hour