2011年12月29日星期四

第9天第4节: 接口、对象多态性



===Interface
-A interface is a class which contains only globle constant and abstract methods
Example:
interface A {
public static final String NAME="TRYME"
public abstract void printA();
}

-Where "public static final" and "public abstract" could be ommited
Example:
interface A {
String NAME="TRYME";
void printA();
}
interface B {
String SUB="ME";
void printB();
}

-Interface with normal class: interface must has iclass ( or interface and finally normal class)
-derived class must override all abstract method
-A derived class can inherit from multiple interfaces
class X implements A,B {
public void printA() {
System.out.println( "hello");
}
public void printB() {
System.out.println("world");
}
}

-derived class can inherit from both abstract class and implements interfaces
public abstract class C {
public abstract void printC();
}
public class X extends C implements A,B {
public void printA() {
System.out.println( "hello");
}
public void printB() {
System.out.println("world");
}
public void printC() {
System.out.println("!!!");
}
}

-abstract class can implements interface
-no methods implementation needed
abstract class D implements A {
public abstract void printD() {
System.out.println("DDD");
}
}
class X externd D {
public void printA () {.....}
public void printD () {.....}
}

-Interface inherits Interface
-use "extends"
-must implments all mothds
interface C extends A,B {
public void printC();
}
class X implements C {
public void printA() {....}
public void printB() {....}
public void printC() {...}
}

==Polymorphism
public class A { public void fun1() {...}}
public class B extends A { public void fun1() {...}
B b = new B();
A a = b;
a.fun1()  ==> calls B->fun1()
--note object a can only use method defined in class A, it calls B's method if it is overridden;
--automatically casting


A a = new B();
B b = (B) a;
a.fun1()  ==> calls B->fun1()
--note object b can use method defined in class B, it calls B's method if it is overridden;
--the original object must defined as class B


A a = new A();
B b = (B) a;
--Compilation Error: because A don't knows B's all field and methods

-Example: define a method with can get a argument of any derived class from A
public class Demo {
public static void main(String args[] ) {
    fun(new A());
    fun(new B());
}
public static void fun(A a) {
    a.fun1();
}

==instanceof
instanceof is used to determine if an object a given class.
class B extends A
A a = new A();
A b = new B();
a instanceof A  ==> true, a instanceof B ==> faluse
b instanceof A ==> true, b instanceof B ==>true


==rule?
let a class inherit only from abstract class or interface, not from a normal class?



没有评论: