一、封装:
使用简单的基础数据类型(属性),方法可以封装成更复杂,更好用的类
java里没有就封装
2、有,但是不好用就封装
每一个类都是封装
二、继承
- 使用extends关键字实现。
- 单继承,一个爹可以有多个儿子,一个儿子只能有一个爹。
- 有个 顶级父类叫Object,所有的对象都有一个父类叫Object,这是规定,记住。所以所有的对象都能调用object的所有方法,比如toString()。
- new一个子类,一定会先new一个父类,子类的构造方法中第一句默认就是super(),意思就是构造子类一定会先构造一个子类。
/**
* @author nnn
**/
public class Father {
public Father(){
System.out.println("父类被创建");
}
public void say(){
System.out.println("我是父类");
}
}
/**
* @author nnn
**/
public class Son extends Father {
public Son(){
super();
System.out.println("子类被创建!");
}
}
/**
* @author nnn
**/
public class Test {
public static void main(String[] args) {
Son son = new Son();
}
}
结果--
父类被创建
子类被创建!
思想:一个对象调用方法的时候,首先去自己的类里边找,找不到的话就去父类找,父类找也不到,就去父类的父类找,直到Object,找到为止!
三、多态
存在的前提
1、要有继承
//先定义一个父类
public class Animal {
private String type;
public Animal(String type) {
this.type = type;
}
//所有的动物都能吃
public void eat(){
System.out.println("动物在吃食物");
};
public void breathe(){
System.out.println("呼吸");
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
2、要有重写
//有继承
public class Dog extends Animal {
public Dog(String type) {
super(type);
}
//狗有狗的吃方法
//有重写
@Override
public void eat() {
System.out.println(this.getType() + "在吃骨头!");
}
public void enjoy(){
System.out.println("摇尾巴!");
}
}
//有继承
public class Cat extends Animal {
public Cat(String type) {
super(type);
}
//有重写
@Override
public void eat() {
System.out.println(this.getType() +"在吃鱼!");
}
}
3、要有父类引用指向子类对象
public class Test {
public static void main(String[] args) {
//父类引用指向子类对象,子类能完成父类的一切工作
Animal dog= new Dog("小狗");
dog.eat();
//父类引用指向子类对象,子类能完成父类的一切工作
Animal cat = new Cat("小猫");
cat.eat();
}
}
--结果
小狗在吃骨头!
小猫在吃鱼!
好处、灵活
public class Girl {
public void KeepAnimal(Animal animal){
System.out.println("小姑娘开始给"+animal.getType()+"喂食。");
System.out.println("小姑娘开始给"+animal.getType()+"喂食。");
//没有重写的方法,调用时就不叫多态
animal.breathe();
//重写了的方法会根据传入的实际的动物调用
animal.eat();
}
}
public class Test {
public static void main(String[] args) {
Animal dog= new Dog("小狗");
Animal cat = new Cat("小猫");
//武三水养了条狗
Girl wss = new Girl();
wss.KeepAnimal(dog);
//刘慧慧养了一只猫
Girl lhh = new Girl();
lhh.KeepAnimal(cat);
//这样让girl 养动物很灵活
}
}