面向对象实现
属性赋值
内部决定
属性声明时赋值
对象创建时就有了
Rect.java
1 2 3 4 5 public class Rect { private Point origin = new Point(0, 0); private int width; private int height;}
Driver.java
1 2 3 4 5 6 7 public class Driver { ... public static void main(String[] args) { Rect rect = new Rect(); } ...}
构造方法内赋值
对象创建后就有了
Rect.java
1 2 3 4 5 6 7 8 9 public class Rect { private Point origin; private int width; private int height; public Rect() { this.origin = new Point(0, 0); }}
Driver.java
1 2 3 4 5 6 7 public class Driver { ... public static void main(String[] args) { Rect rect = new Rect(); } ...}
外部注入
构造方法传参赋值
对象创建后就有了
Rect.java
1 2 3 4 5 6 7 8 9 10 11 public class Rect { private Point origin; private int width; private int height; public Rect(Point origin, int width, int height) { this.origin = origin; this.width = width; this.height = height; }}
Driver.java
1 2 3 4 5 6 7 public class Driver { ... public static void main(String[] args) { Rect rect = new Rect(new Point(1, 2), 3, 4); } ...}
Setter 赋值
被设置时才有
Rect.java
1 2 3 4 5 6 7 8 9 public class Rect { private Point origin; private int width; private int height; public void setOrigin(Point origin){ this.origin = origin; }}
Driver.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class Driver { ... public static void main(String[] args) { Point p1 = new Point(1, 2); Rect rect = new Rect(); rect.setPoint(p1); rect.setWidth(3); rect.setHeight(6); int right = rect.maxY(); System.out.println(right); } ...}
不一定需要赋值
属性的意义
有
案例
原形 有 圆心
public class Circle { private Point center; }
汽车 有 轮子
public class Car { private Wheel wheel1; private Wheel wheel2; private Wheel wheel3; private Wheel wheel4; }
玩家 有 武器
public class Player { private Weapon mainWeapon; }
属性空值状态
属性赋值方法 123 都会导致 对象在创建后 属性一定会有对象
属性赋值方法 4 对象在创建后 属性值是 null,直到 setter 调用后 才有对象
public class Driver { psvm() { Player p1 = new Player(); // now , p1.weapon => null; p1.setWeapon(new Weapon()); } }
分析业务
原形 和 圆心
玩家 和 主武器
空指针验证
对于 玩家 和 主武器 的逻辑关系
Player 的 weapon 属性 不一定有对象
写代码时,需要进行空指针验证
public class Wepaon { private int atk; ... }
public class Player { private int atk; private Wepaon weapon; public int totalAtk() { int atk = this.atk; if (weapon != null) { atk += weapon.getAtk(); } return atk; } }
面向对象编程方法
基本步骤
搞设计
根据需求, 变为类设计 (类, 方法, 属性 的声明)
搭架子
根据设计, 构建 类的结构代码
填代码
填写每个方法内的执行代码
做测试
测试填写的每一个方法是不是都是对的
搭架子
建 类
填 属性
填 Getter Setter
填 构造器
架 方法
填代码
想清楚
你有什么?资源?数据
要干什么?责任?任务
产出什么?返回值
资源
属性
参数
局部变量
做测试
单元测试