Java程序设计 Java Programming Fall, 2013 Contents Single vs. Multiple Inheritance Abstract Classes Interface Chapter 7 Interfaces 2/44 Single vs. Multiple Inheritance Some object-oriented languages (eg.: C++) allow multiple(多重的) inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents; The price(代价): collisions(冲突), such as the same variable name, same method name in two parents, have to be resolved; Chapter 7 Interfaces 3/44 Single vs. Multiple Inheritance Java decision: single inheritance for classes, meaning that a derived class can have only one parent class; However, in most cases, the use of interfaces(接口) gives us aspects of multiple inheritance without the overhead (will discuss later). Chapter 7 Interfaces 4/44 abstract Classes(抽象类) An abstract class is a conceptual class,表示的是“is-a”关 系. abstract class provides a common root for a group of classes--共性; use the modifier abstract on a class header to declare an abstract class: abstract class className { } …… Chapter 7 Interfaces 5/44 Inheritance (继承) Example: Book Dictionary Novel Mystery Romance Chapter 7 Interfaces 6/44 Abstract Classes (抽象类) An abstract class often contains abstract methods, though it doesn’t have to abstract methods consist of only methods declarations, without any method body. When a class contains one or more abstract methods, it should be declared as abstract class; The abstract methods of an abstract class must be defined in its subclass; We cannot declare abstract constructors or abstract static methods. Chapter 7 Interfaces 7/44 Abstract Classes abstract class ClassName { //variables … abstract dataType MethodName1(); //抽象方法 … … dataType Method2() { // method body 已实现的方法, } 即:非抽象方法 } 8 //Animal.java public abstract class Animal { public String name; public int age; public void print() { System.out.println("名字:"+name); System.out.println("大小:"+age); } public abstract void run(); public abstract void cry(); } 9 Abstract Classes (抽象类) public class AAnimal //错误 { public String name; public int age; 修改为 public abstract class AAnimal public void print() { System.out.println("名字:"+name); System.out.println("大小:"+age); } public abstract void run(); } public abstract void cry(); Chapter 7 Interfaces 10/44 Abstract Classes(抽象类) 实例化-由类创建对象/实例. An abstract class cannot be instantiated (实例化): objects cannot be created(对象不能被创建); 它只能做为父类使用,由它派生的子类必须实现抽象类中所 有的抽象方法,才能创建对象。 在abstract class 中可以有自己的数据成员,也可以 有非abstarct的成员方法。 Chapter 7 Interfaces 11/44 Abstract Class -Example Shape is an abstract class. Shape Circle Rectangle Chapter 7 Interfaces 12/44 The Shape Abstract Class public abstract class Shape { //method declaration public abstract double area(); } public void move() { // non-abstract method // implementation } • Is the following statement valid? – Shape s = new Shape(); • No. It is illegal because the Shape class is an abstract class, which cannot be instantiated (实例化) to create its objects. 13 The Shape Abstract Class public Circle extends Shape { protected double r; protected static final double PI =3.14159; public Circle() { r = 1.0; ) public double area() { return PI * r * r; } … } public Rectangle extends Shape { protected double w, h; public Rectangle() { w = 0.0; h=0.0; } } public double area() { return w * h; } 14 Abstract Class Properties A class with one or more abstract methods is automatically abstract and it cannot be instantiated (实例化); A class declared abstract, even with no abstract methods can not be instantiated; A subclass of an abstract class can be instantiated if it overrides(重载) all abstract methods by implementation(实现) them; A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated (实例化). 15 Example: //Animal.java public abstract class Animal { public String name; public int age; public void print() { System.out.println("名字:"+name); System.out.println("大小:"+age); } public abstract void run(); 16 Example: class Dog extends Animal { String type; public Dog() { type="宠物狗"; } public void run(){ } public void cry() { System.out.println ("汪汪叫"); } } class Test { public static void main(String[]args) { Dog a =new Dog(); a.name="欢欢"; a.age=2; a.print(); a.cry(); System.out.println ("这是一只"+a.type); } } 17 Interface interface is a conceptual entity similar to an abstract class. interface表示的是"like-a"关系。 contain only constants (常量,final variables) and abstract method (no implementation) - Different from Abstract classes. 接口中定义的变量默认是public static final 型,且必须初 始化,所以实现类中不能重新定义,也不能改变其值。 接口中的方法默认都是 public,abstract 类型的。 Chapter 7 Interfaces 18/44 Interface(接口) A Java interface is a collection of constants and abstract methods. abstract method: a method header without a method body; we declare an abstract method using the modifier abstract; since all methods in an interface are abstract, the abstract modifier is usually left off(省略). Chapter 7 Interfaces 19/44 //格式: InterfaceName.java interface InterfaceName { //Constant/Final Variable Declaration //Methods Declaration–only method header } //接口示例:Printable.java interface Printable { final int MAX=100; } Printable.java void add(); float sum(float x,float y); 20 Interfaces A class can implement(实现) any number of interfaces, but cannot extend more than one class at a time. Therefore, interfaces are considered as an informal way to implement multiple inheritance in Java. Chapter 7 Interfaces 21/44 Interfaces A class formally implements an interface by Using keyword in the class header in the implements clause; a class can implement multiple interfaces: the interfaces are listed in the implements clause, separated by commas(逗号). If a class asserts(声称) that it implements(实现) an interface, it must define all methods in the interface or the compiler will produce errors. Chapter 7 Interfaces 22/44 Defining Interface interface InterfaceName { //Constant/Final Variable Declaration //Methods Declaration–only method header } class ClassName implements InterfaceName [, InterfaceName2, …] { // Body of Class } 23 Interface - Example <<Interface>> Speaker speak() Politician Lecturer speak() speak() Chapter 7 Interfaces 24/44 interface Speaker { public void speak( ) ; } Speaker.java class Politician implements Speaker { public void speak() { System.out.println(“Talk politics”); } } Politician.java class Lecturer implements Speaker { Lecturer.java public void speak() { System.out.println(“Talks Object Oriented Design and Programming!”); } } 25 Interface Inheritance(接口的继承) Like classes, interfaces can also be extended(扩展,继承); Interfaces, unlike classes, can extend more than one other interface; The new sub-interface will inherit all the members of the superinterface similar to classes’ inheritence. This is achieved by using the keyword extends as follows: interface InterfaceName2 extends InterfaceName1,… { // Body of InterfaceName2 } Chapter 7 Interfaces 26/44 Interface Inheritance — interface J { int j = 200; int j1(); } class I implements L { public int j1() { return 4; } public double k1() { return 6.8; } interface K { double k1(); } interface L extends J, K { boolean l1(); } Example 1 } public boolean l1() { return true; } 27 class InterfaceInheritance { public static void main(String args[ ]) { I i = new I(); System.out.println(i.j); System.out.println(i.j1()); System.out.println(i.k1()); System.out.println(i.l1()); } } Result : 200 4 6.8 true 28 Interface Inheritance — Example 2 • Class A implements two interfaces: I1 & I2. But these two interfaces have the same variable and method. • In class A, the method of these two interfaces is implemented only once. • For variables with the same name, we need to type-case(强制数据类型转换) them when accessing them; otherwise, compile error will occur if a variable with the same name is used. 29 interface I1{ int nValue = 1; void amethod(); } public class A implements I1, I2 { public void amethod() { System.out.println("Hello word!"); } interface I2 { int nValue = 2; void amethod(); } public static void main(String[] args) { A q = new A(); q.amethod(); 执行結果: Hello world! 1 2 //Compile Error //System.out.println(q.nValue); System.out.println(((I1) q).nValue); System.out.println(((I2) q).nValue); } } 30 Interface Inheritance — Example 2 interface Base { int base = 0; int ambiguous = 10; } interface Set1 extends Base { int set1 = 1; int ambiguous = 100; } interface Set2 extends Base { int set2 = 2; int ambiguous = 1000; } 31 //Example 1: 接口继承 class AmbiguousVariable implements Set1 { public static void main(String args[]) { AmbiguousVariable z = new AmbiguousVariable(); System.out.println(z.base); //0 System.out.println(z.set1); //1 System.out.println(z.ambiguous); //100 System.out.println(((Base)z).ambiguous); //10 System.out.println(((Set1)z).ambiguous); //100 } } 0 1 100 10 100 32 class AmbiguousVariable implements Set1, Set2 { public static void main(String args[]) { AmbiguousVariable z = new AmbiguousVariable(); System.out.println(z.base); //0 System.out.println(z.set1); //1 //System.out.println(z.ambiguous); //编译错误 System.out.println( ((Base)z).ambiguous); //10 System.out.println( ((Set1)z) .ambiguous); //100 System.out.println( ((Set2)z) .ambiguous); //200 } } 0 1 10 100 200 33 Inheritance and Interface Implementation A general form of interface implementation: class ClassName extends SuperClass implements InterfaceName […, InterfaceName2, …] { // Body of Class } This shows a class can extended another class while implementing one or more interfaces. It appears like a multiple inheritance (if we consider interfaces as special kind of classes with certain restrictions or special features). 34 Example Abstract class:Shape Interface:2D-Shape implements extends Circle Rectangle Chapter 7 Interfaces 35/44 public abstract class Shape { public abstract void setColor(String str); } interface Shape2D { } final double pi = 3.14; public abstract double area(); class Circle extends Shape implements Shape2D { double radius; String color; public Circle(double r) { redius = r; } public void setColor(String str) { color = str; System.out.println(“color is “+color); } } public double area() { return (pi*radius*radius); } 36 Reference data types(引用数据类型) The reference(引用) types are 1. class(类) types 2. interface (接口) types 3. array(数组) types Variables of these types can refer to objects(指向对 象) of the corresponding type. Chapter 7 Interfaces 37/44 public class ShapeTest { public static void main(String[] args) { Shape2D s; //声明接口的引用数据 s = new Circle(1.0); //通过实现接口的类创建接口的引用数据 s.area(); //只能调用接口中定义的方法 //s.setColor(“red”); //否则,就是语法错误 } } 38 Person.java 综合实例: 如何声明和使用 以接口和抽象类 为类型的数据 (P39-42)。 public abstract class Person { String name; int age; {//初始化块 name ="Parent"; age = -1; } Speaker.java interface Speaker { public void speak( ); } public void initiate(String name, int age){ this.name = name; this.age = age; } public void display() { 39 System.out.println(name+","+a ge); Politician.java public class Politition extends Person implements Speaker { public Politition(String name, int age){ super.initiate(name, age); } public void speak(){ System.out.println("Talk politics"); } } void detailInfo(){ System.out.println("Polition Implementation"); } 40 Lecturer.java public class Lecturer extends Person implements Speaker { public void speak(){ System.out.println("Talks OO Design and Programming!"); } void detailInfo(){ System.out.println("Lecturer Implementation"); } } 41 public class Test { public static void main(String[ ] args) { test.java Speaker speaker; Person person; Politition p = new Politition("Child", 60); p.display(); Lecturer l = new Lecturer(); l.display(); speaker = p; speaker.speak(); speaker = l; speaker.speak(); person = p; person.detailInfo(); person = l; 42 Java类实现了一个接口,继承了一个类,如何访问接口与父 类中相同的变量: class Aclass { int num=10; } interface Ainterface { int num=1; void method(); } public class Test extends Aclass implements Ainterface { public void method() { System.out.println("***Test***"); } public static void main(String[] args) { Test t = new Test(); System.out.println("Aclass's num:"+ ((Aclass)t).num); System.out.println("Ainterface's num:"+ ((Ainterface)t).num); t.method(); ((Ainterface)t).method(); } } 43 对象类型转换 Java中,两个具有继承关系的对象之间可以转换,具体限制: 两个转换的对象之间应该具有继承关系,也就是说只是在子类和父 类的对象之间进行转换,而不是任意两个类。 一个子类对象的类型可以向上转换成它的父类类型,这个转 换过程是安全的。因为父类所具有的信息,子类一般全有。 当然,转换过程中会丢失属于子类而不属于父类的信息。 Chapter 7 Interfaces 44/44 对象类型转换 设A类是B类的父类,用子类B创建一个对象,并 把这个对象的引用放到父类的对象中时,如: A a; a=new B(); //上转型对象 A a; B b=new B(); a=b; //上转型对象 称父类对象a是子类对象b的上转型对象。 对象的上转型对象的实体是子类负责创建的,但 上转型对象会失去原对象的一些属性和功能。 45 上转型对象的特点: 对象的上转型对象 子类对象 继承或重写的变量和方法 新增的变量和方法 •上转型对象不能操作子类新增的成员变量和方法 •上转型对象可以操作子类继承或重写的变量和方法 •如果子类重写了父类的某个方法,对象上转型对象调 用时一定是调用这个重写的方法 46 例: 水果 苹果 桔子 红富士苹果 47 注意: •父类创建的对象和子类对象的上转型对象不是一个含义 •可以将对象的上转型对象再强制转换到一个子类对象,这时该 子类对象又具备该子类所有的属性和功能。 •不可以将父类创建的对象的引用赋值给子类声明的对象。 •如果需要把一个父类对象转换成子类类型,则需要强制转换。 如: (这样会导致异常) A a=new A(); B b=(B)a; •类型测试运算符 instanceof表达式格式: 对象引用 instanceof 类名或接口名 48 例(上转型对象、instanceof运算符): class Person { static int age; } //age=0 public String detailInfo() { return ("一个人"); } class Student extends Person { String info=detailInfo()+"of"+super.detailInfo(); } public String detailInfo() { return "一个学生"; } 49 测试:Person.java & Student.java public class Extend { public static void main(String[] args){ Student stu1=new Student(); System.out.println(stu1 instanceof Person); //true Person p1=new Person(); System.out.println(p1 instanceof Student); //false 运行结果: true false 0 一个学生of一个人 0 一个学生 一个学生 true true p1=stu1; //上转 System.out.println(stu1.age); //0 System.out.println(stu1.info); //一个学生of一个人 System.out.println(p1.age); //0 //System.out.println(p1.info); //错误 System.out.println(p1.detailInfo()); System.out.println(((Person)p1).detailInfo()); //一个学生 //一个学生 System.out.println(p1 instanceof Student); System.out.println(p1 instanceof Person); //true //true 此语句编译 时报错:无 法解析 p1.info,非 法访问 } } 50