1,面向对象三大特性:继承,封装,多态
2,继承:xx是一种xx
public class Cat extends Animal
子类 父类,基类,超类
作用:简化代码(减少代码冗余)
构造方法:父类对象先与子类对象创建
super():调用父类构造函数
重写:当父类方法不能满足子类需求 方法名相同,参数也得相同,子类重写方法访问修饰符不能比父类更严格
equals 与 hashcode一起使用
public class Vehicles {
public String brand;
public String color;
public void run(){
System.out.println("我已经开动了");
}
public void showInfo(){
System.out.println("商标"+brand+" "+"颜色"+color);
}
public Vehicles(String brand, String color) {
this.brand = brand;
this.color = color;
}
public Vehicles() {
this.brand = brand;
this.color = color;
}
}
public class Car extends Vehicles{
public int seats;
public void showCar(){
System.out.println("商标"+brand+" "+"颜色"+color+" "+"座位"+seats);
}
public Car(String brand, String color, int seats) {
super(brand, color);
this.seats = seats;
}
public static void main(String[] args){
Car c = new Car("宝马","白色",5);
c.showCar();
}
}
public class Truck extends Vehicles {
public float load;
public void showTruck(){
System.out.println("商标"+brand+" "+"颜色"+color+" "+"载重"+load);
}
public Truck(String brand, String color, float load) {
super(brand, color);
this.load = load;
}
public static void main(String[] args){
Truck t = new Truck("解放","白色",45000);
t.showTruck();
}
}
商标宝马 颜色白色 座位5
商标解放 颜色白色 载重45000.0
3,访问修饰符 本类 同包 继承 无限制
public --公有 T T T T
protected --受保护的 T T T
默认 T T
private --私有的 T
public class Animal1 {
public final String name ;
public Animal1(){
final int a;
a = 1;
name = "";
}
public final void eat(){
System.out.println("吃饭");
}
protected void sleep(){
System.out.println("睡觉");
}
void say(){
System.out.println("说话");
}
private void run(){
System.out.println("跑");
}
}
4,static – 静态的,全局唯一 Math
静态方法中不能出现非静态元素
5,final 不可变的 – 类:不能有子类
属性:必须赋初值,若不赋初值,需要在构造函数中赋初值,一旦赋值, 值不能被改变
方法:不能被重写
局部变量:可以不赋初值。一旦赋值,值不能被改变