面向对象设计 - 入门
info
OOD 面向对象设计 对于 Entry level SDE 考察综合素质. 实现系统的 Viability, 典型例题是 Design Elevator System.
前置知识
封装 Encapsulation
Class
Object
class Animal {};
Animal a = new Animal();
class Employee {
// access modifier
private String name;
private float salary;
private int level;
// 外部可调用
public void raiseSalary();
public void printName();
public void promoteLevel();
public Sring getName();
}
继承 Inheritance
- It describes a IS-A relationship.
- 子类继承父类里所有不是 private 的 attributes.
- 父类 =
Base class
/Parent class
, 子类 =Sub class
. - super keyword will call Base class's same name method.
- final class 不能被继承.
- abstract class can not 初始化.
class Animal {
public void description(){
System.out.println("This is a general animal");
}
protected String name;
public int id;
private String privacy;
}
class Dog extends Animal {
// override
public void description() {
System.out.println("This is a Dog");
System.out.println("Name -> " + name);
System.out.println("Id -> " + id);
// System.out.println("Privacy -> " + privacy); // WRONG
}
// overload
public void description(String type) {
System.out.println("This is a " + type);
}
}
Dog dog = new Dog();
dog.description();
dog.description("Cat");
class Dog extends Animal {
public void description() {
super(); // This will call Base class's same name method.
}
}
Interface
- Interface can have only abstract methods.
- Interface can't provide the implementation of abstract class.
interface Service {
// No constructor
// interface里的函数都是抽象函数,不可以有Implement.
// Interface can have only abstract methods.
public void serve();
public void retire();
}
class Dog implements Service {
public void serve() {
// dog in service
}
public void retire() {
// dog retire from service
}
}
多态 Ploymorphism
abstract class Animal {
public abstract void makeSound();
}
final class Dog extends Animal {
public void makeSound() {
System.out.println("Woof !");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Meeow !");
}
}
Animal animal1 = new Dog(); // CORRECT
Animal animal2 = new Cat(); // CORRECT
// the same Animal class, the same makeSound() method -> the different output.
animal1.makeSound(); // Woof !
animal2.makeSound(); // Meeow !
枚举变量 Enum
- 可读性好.
- 防止被外部传入错误的参数, like
4, 5, 6
.
public enum TrafficSignal {
// defined in compile time
RED, YELLOW, GREEN
}
public class Testing {
TrafficSignal signal = TrafficSignal.RED;
}
异常处理 Exception
- Checked Exception (IO Exception, Compile time exception)
- Unchecked Exception (Runtime, Exception, NPE)
class MyException extends Exception {
public MyException(String s) {
super(s);
}
}
class Testing {
public void test() {
try {
throw new MyException("My exception");
}
catch (MyException ex) {
System.out.println(ex.getMessage()); // you will get "My exception"
}
}
}
Testing test1 = new Testing();
test1.test();
public class ExceptionTest2 {
public void test() throws MyException {
if (true) {
throw new MyException("My exception");
}
}
public void test1() {
// test(); // WRONG
}
public void test2() throws MyException {
test(); // CORRECT
}
// 用try catch handle exception
public void test3() {
try {
test(); // CORRECT
} catch (MyException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) throws MyException {
ExceptionTest2 t = new ExceptionTest2();
t.test2();
t.test3();
}
}
S.O.L.I.D 原则
Single responsibility principle 单一责任原则
一个类应该有且只有一个去改变它的理由,意味着一个类应该只有一项工作.
// 只负责 calculate area
public class AreaCalculator {
private float result;
public float getResult() {
return this.result;
}
public float calculateArea(Triangle t) {
this.result = h * b / 2;
}
}
// 只负责 print
public class Printer {
public printInJson(float number) {
jsonPrinter.initialize();
jsonPrinter.print(this.result);
jsonPrinter.close();
}
}
Open close principle 开放封闭原则
对象或者实体应该对扩展开发,对修改封闭 (Open to extension, close to modification).
public interface Shape {
public float getArea();
}
public class Triangle implements Shape {
public float getArea() {
return b * h / 2;
}
}
// 不需要改变,只需要取定义新的形状
public class AreaCalculator {
private float result;
public float getResult() {
return this.result;
}
public float calculateArea(Shape s) {
this.result = s.getArea();
}
}