当实例化子类时(创建对象时)父类做了什么:
继承案例:
代码示例:
import java.util.*;
class Vehicle{
String brand;
String number;
public double getsumrent(int days){
return 0;
}
public Vehicle(){
}
public Vehicle(String brand,String number){
this.brand = brand;
this.number = number;
}
}
class Car extends Vehicle{
String type;
public Car(){
System.out.println("请输入小轿车车型:");
Scanner input = new Scanner(System.in);
String c = input.next();
this.type = c;
}
public Car(String brand,String number,String typs){
super(brand,number);
this.type = type;
}
public double getsumrent(int days){
switch(this.type){
case "两厢":
return 300 * days;
case "三厢":
return 350 * days;
case "越野":
return 500 * days;
default :
return 0;
}
}
}
class Bus extends Vehicle{
int num;
public Bus(){
System.out.println("请输入座位数:");
Scanner input = new Scanner(System.in);
int i = input.nextInt();
this.num = i;
}
public Bus(String brand,String number,int num){
super(brand,number);
this.num = num;
}
public double getsumrent(int days){
if(this.num <= 16){
return 400 * days;
}
else {
return 600 * days;
}
}
}
class Test{
public static void main(String[] args){
String s1 = "小轿车";
String s2 = "大巴车";
System.out.println("请输入车型:");
Scanner input = new Scanner(System.in);
String s = input.next();
if(s.equals(s1)){
Car c = new Car();
System.out.println("请输入租用天数:");
Scanner ww = new Scanner(System.in);
int d = ww.nextInt();
System.out.println("租金为:" + c.getsumrent(d));
}
else if(s.equals(s2)){
Bus n = new Bus();
System.out.println("请输入租用天数:");
Scanner ee = new Scanner(System.in);
int x = ee.nextInt();
System.out.println("租金为:" + n.getsumrent(x));
}
else {
System.out.println("该车未录入");
}
}
}
多态:
将多个对象调用同一方法,得到不同结果:
注意:
当是多态时,该引用名称只能访问父类中的属性和方法,但是优先访问子类重写以后的方法。
例子:
多态好处: 减少代码的冗余性
多态的两种类型转换:
建议:
递归:
eg:
内存分析: