1. 抽象类(abstract class)
Rules about abstract class:
(1)An abstract class can never be instantiated.
(2)The methods marked abstract end in a semicolon rather than curly braces.
(3)You can, however, put nonabstract methods in an abstract class.
(4)It is legal that an abstract class has no abstract methods.
Example:
1)several rules applied
abstract class Animal { // default, package access
protected int age;
private String name = "Animal";//yes, abstract class can has private fields
private String getName() { //yes, abstract class can has private non-abstract method
return name;
}
abstract void eat(String food);//abstact method ends in a semicolon, default acess
//never, ever, ever mark methods as both private and abstract
public void setAge(int age) { //abstract class can has non-abstract methods
this.age = age; //ok, use this keywords
}
//public static abstract void info();
//illegal combination of modifiers: abstract and static
public static void info() { //ok, has static non-abstract class
System.out.println("Oh, Animal");
}
}
abstract class Dog {} //ok, nothing
abstract class Cat { //ok, abstract class has no abstract methods
public void name() {
System.out.println("Oh, Cat");
}
public void age() {
System.out.println("Oh, my age is secret!");
}
}
(2) about constructor
abstract class Bird {
int age;
// public abstract Bird(int age); // constructor can not be abstract
public Bird(int age) { //ok
this.age = age;
}
}
2. 接口(interface)
Rules about interface:
(1)All interface methods are implicitlypublic and abstract. In other words, you do not need to actually type thepublic orabstract modifiers int the method declaration, but the method is still alwayspublic andabstract.
(2)All variables defined in an interface must bepublic, static, and final——in other words, interfaces can declare only constants, not instance variables. And in other words, any fiels in an interface are automatically public, static, and final.
(3)Interface methods must not bestatic. Because interface methods are abstract, and combination abstract and static is illegal.
(4)Because interface methods areabstract, they cannot be marked final, strictfp, ornative.
(5)An interface canextend one or more other interfaces.
(6)An interface cannotextend anything but another interface.
(7)An interface cannotimplement another interface or class(of course including abstract class).
(8)Interface types can be used polymorphically.
3. extends ? implements ?
(1)class extends class (at most extends one class)
(2)class implements interface1, interface2, ... (can implements multiple)
(3)class extends class(at most one)implements interface1, interface2, ...
(4)interface extends interface1, interface2, ...(can extendss multiple)
(5)interface can not extends class