java 封装,继承,多态
- 封装:安全性
- 继承:复用性
- 多态:拓展性
- 书写思路:
- 具体代码:
封装:安全性
在对类封装的时候 使用的访问权限是私有的(private),读取和写入数据使用的是get/set方法
继承:复用性
当子类继承(关键字:extends)了父类,那么子类就拥有了父类的所有方法和属性
多态:拓展性
对外的一种形式,对内多种实现
书写思路:
父类
- 第一步写父类名
- 写相应的属性(private)
- 写get,set方法
- 写有参,无参构造方法
- 再写 toString方法
- 可以再写父类的一些的方法
子类
- 第一步写子类名extends父类
- 写相应的属性(private)
- 写get,set方法
- 写有参,无参构造方法
- 再写 toString方法
- 可以再写自己独有的方法,方法可以与父类方法名一致
3、4、5都可以用快捷键快速生成,第五条可写可不写
alt+shift+s
具体代码:
父类代码
package com.encapsulationInheritancePolymorphism.my;public class Animal {private String name;private double weitht;private String color;
// 按住alt+shift+s 快速生成get/set方法public String getName() {return name;}public void setName(String name) {this.name = name;}public double getWeitht() {return weitht;}public void setWeitht(double weitht) {this.weitht = weitht;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}// 有参构造 按住alt+shift+s倒数第三个public Animal(String name, double weitht, String color) {super();this.name = name;this.weitht = weitht;this.color = color;}//无参构造public Animal() {super();}public void show(Animal animal) {System.out.println(animal);}@Overridepublic String toString() {return "Animal [name=" + name + ", weitht=" + weitht + ", color=" + color + "]";}public void run() {System.out.println("animal run!");}}
子类代码
package com.encapsulationInheritancePolymorphism.my;public class Cat extends Animal{private double height;public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public void run() {System.out.println("cat run!");}public void chatchMouse() {System.out.println("猫抓老鼠!");}@Overridepublic String toString() {return "Cat [height=" + height + ", getName()=" + getName() + ", getWeitht()=" + getWeitht() + ", getColor()="+ getColor() + "]";}
}
测试函数
public static void main(String[] args) {
// Animal an=null;Cat an=null;an = new Cat();an.setColor("blaek");an.setWeitht(20.5);an.setName("汤姆猫");an.setHeight(10.0);System.out.println(an.toString());an.run();an.chatchMouse();}