Chapter 4 Advanced Class Features 抽象、接口与多态
主要内容 静态(static)变量与方法,以及初始化 最终(final)类、变量与方法 抽象(abstract)类与方法 接口(interface) 多态
static keyword
static Keyword static 用于修饰变量、方法和内部类
类的静态变量 被类的所有对象实例共享
Class Attributes 具有public权限则可以被直接访问 public class OtherClass { public void incrementNumber() { Count.counter++; }
类的静态方法 public class Count { private int serialNumber; private static int counter = 0; public static int getTotalCount() { return counter; } public Count() { counter++; serialNumber = counter; OUTPUT: Number of counter is 0 Number of counter is 1 public class TestCounter { public static void main(String[] args) { System.out.println("Number of counter is " + Count.getTotalCount()); Count count1 = new Count(); }
静态模块的初始化 一个类可以包含一个静态代码块(不属于任何方法) 静态代码块只在类加载时执行一次 静态代码块一般用于初始化静态属性
Static Initializers public class Count { public static int counter; } public class TestStaticInit { public static void main(String args[]) { System.out.println("counter = " + Count.counter);
Singleton
单态(Singleton)设计模式
Singleton code:
Usage code: package shipping.reports; import shipping.domain.*; public class FuelNeedsReport { public void generateText(PrintStream output) { Company c = Company.getCompany(); // use Company object to retrieve the fleet vehicles }
多线程时的单体模式 class Singleton { private static Singleton instance; private Singleton() { ... } public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } ... public void doSomething() { ... }
double-checked locking (con.) class Singleton { private static Singleton instance; private Singleton() { ... } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } ... public void doSomething() { ... }
final keyword
final Keyword final 类不能被继承 final 方法不能被重写 final 变量是常数 空白最终变量(blank final variable):即只定义没赋值的变量 空白最终变量可以在构造方法中赋值 空白最终变量要在使用之前赋值
Final Variables Constants: public class Bank { } private static final double DEFAULT_INTEREST_RATE=3.2; // percent ... // more declarations }
Final Variables Blank Final Instance Attribute: public class Customer { private final long customerID; public Customer() { customerID = createID(); } public long getID() { return customerID; private long createID() { return ... // generate new ID ... // more declarations
Abstract class
抽象(Abstract)类: Scenario
Fleet initialization code: public class ShippingMain { public static void main(String[] args) { Company c = Company.getCompany(); // populate the company with a fleet of vehicles c.addVehicle( new Truck(10000.0) ); c.addVehicle( new Truck(15000.0) ); c.addVehicle( new RiverBarge(500000.0) ); c.addVehicle( new Truck(9500.0) ); c.addVehicle( new RiverBarge(750000.0) ); FuelNeedsReport report = new FuelNeedsReport(); report.generateText(System.out); }
FuelNeedsReport code: public class FuelNeedsReport { public void generateText(PrintStream output) { Company c = Company.getCompany(); Vehicle v; double fuel; double total_fuel = 0.0; for ( int i = 0; i < c.getFleetSize(); i++ ) { v = c.getVehicle(i); // Calculate the fuel needed for this trip fuel = v.calcTripDistance() / v.calcFuelEfficency(); output.println("Vehicle " + v.getName() + " needs " + fuel + " liters of fuel."); total_fuel += fuel; } output.println("Total fuel needs is " + total_fuel + " liters.");
Abstract Classes: Solution
Abstract Classes: Solution public abstract class Vehicle { public abstract double calcFuelEfficiency(); public abstract double calcTripDistance(); } public class Truck extends Vehicle { public Truck(double max_load) {...} public double calcFuelEfficiency() { public double calcTripDistrance() { public class RiverBarge extends Vehicle { public RiverBarge(double max_load) {...} /* calculate the fuel efficiency of a river barge */ /* calculate the distance of this trip along the river-ways */
模板方法Template Method 设计模式
Interfaces
接口Interfaces Java的接口(interface)只声明方法,不实现方法体 相互无关的类可以实施同一个接口 一个类可以实施多个无关的接口
在UML的接口图和类图相似,只是在名称上方使用<<interface>>指明接口
交通工具 车辆 船 飞机 喷气式飞机 非机动车 汽车 柴油机船 划艇 Interface 燃油
Interface Example public interface Flyer { public void takeOff(); public void land(); public void fly(); } public class Airplane implements Flyer { public void takeOff() { // accelerate until lift-off // raise landing gear public void land() { // lower landing gear // deccelerate and lower flaps until touch-down // apply breaks public void fly() { // keep those engines running
Interface Example
Interface Example public class Bird extends Animal implements Flyer { public void takeOff() { /* take-off implementation */ } public void land() { /* landing implementation */ } public void fly() { /* fly implementation */ } public void buildNest() { /* nest building behavior */ } public void layEggs() { /* egg laying behavior */ } public void eat() { /* override eating behavior */ } }
Interface Example
Interface Example public class Airport { public static void main(String[] args) { Airport metropolisAirport = new Airport(); Helicopter copter = new Helicopter(); SeaPlane sPlane = new SeaPlane(); Flyer S = Superman.getSuperman(); // Superman is a Singleton metropolisAirport.givePermissionToLand(copter); metropolisAirport.givePermissionToLand(sPlane); metropolisAirport.givePermissionToLand(S); } private void givePermissionToLand(Flyer f) { f.land();
声明接口 接口是一种特殊的类,由常量和抽象方法组成。 例: public interface AudioClip { public void play(); public void loop(); public void stop(); } 接口也有继承性,一个接口可以继承一个以上的父接口。 public interface AudioClipSub extends AudioClip1, AudioClip2{ }
Tasks: 设计一副有54张的扑克牌,并实现: 能通过洗牌获得随机排序的牌; 可以根据需要抽取任意张牌; 可以根据玩家人数发牌;