这两周学习了面向对象的一些知识,从之前学的推箱子开始就有一点小接触。带着这些不懂和为什么,我们开了新章节面向对象。从封装--继承--多态,都是一知半解的状态,虽然这部分知识不需要逻辑思维,但是就是一时懂不彻底。老师的多次实例讲解,我们上机,课后作业做着。感觉还是很有收获的,最少现在我懂了,并且能有思绪的写出它们:
public abstract class Car {
protected String color;//颜色
protected String pinpai;//品牌
protected int numOfwheels;//车轮数量
//setter和getter
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getPinpai() {
return pinpai;
}
public void setPinpai(String pinpai) {
this.pinpai = pinpai;
}
public int getNumOfwheels() {
return numOfwheels;
}
public void setNumOfwheels(int numOfwheels) {
this.numOfwheels = numOfwheels;
}
//构造方法
public Car(String color, String pinpai, int numOfwheels) {
super();
this.color = color;
this.pinpai = pinpai;
this.numOfwheels = numOfwheels;
}
//跑的方法
public abstract void run();
}
public class Bus extends Car {
private int max;//最大载客量
//setter,getter
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public Bus(String color, String pinpai, int numOfwheels,int max) {
super(color, pinpai, numOfwheels);
this.max=max;
}
//跑
@Override
public void run() {
System.out.println("一辆公共汽车在公路上跑!!!");
}
//报站的方法
public void baozhan(){
System.out.println("***站到了,下车的乘客请从后门下车。。。。");
}
@Override
public String toString() {
return "一辆"+this.color+"的"+this.pinpai+"的,"+this.numOfwheels+"个轮子的,载客"+this.max+"个人公交车";
}
}
public class Truck extends Car {
private int zaizhong;//载重量
//setter,getter
public int getZaizhong() {
return zaizhong;
}
public void setZaizhong(int zaizhong) {
this.zaizhong = zaizhong;
}
public Truck(String color, String pinpai, int numOfwheels,int zaizhong) {
super(color, pinpai, numOfwheels);
this.zaizhong=zaizhong;
}
//跑
@Override
public void run() {
System.out.println("一辆载重卡车在高速上跑!!!");
}
//装货
public void zhuang(){
System.out.println("员工正在装货!!!");
}
//卸货
public void xie(){
System.out.println("员工正在卸货!!!");
}
@Override
public String toString() {
return "一辆"+this.color+"的"+this.pinpai+"的,"+this.numOfwheels+"个轮子的,载重"+this.zaizhong+"吨的卡车";
}
}
public class Test {
public static void main(String[] args) {
//公交车
Bus bus=new Bus("红色","比亚迪",4,30);
bus.run();
bus.baozhan();
System.out.println(bus.toString());
System.out.println("");
//载重
Truck truck=new Truck("红色","大众",4,3);
truck.run();
truck.zhuang();
truck.xie();
System.out.println(bus.toString());
}
}