Java construye las interfaces gráficas del usuario mediante awt
Java 程序设计 Java Programming Fall, 2013. Chapter 7 Interfaces 2/44 Contents Single vs....
-
Upload
amberlynn-fitzgerald -
Category
Documents
-
view
230 -
download
4
Transcript of Java 程序设计 Java Programming Fall, 2013. Chapter 7 Interfaces 2/44 Contents Single vs....
Chapter 7 InterfacesChapter 7 Interfaces 2/44
Contents
Single vs. Multiple Inheritance Abstract Classes Interface
Chapter 7 InterfacesChapter 7 Interfaces 3/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 InterfacesChapter 7 Interfaces 4/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 InterfacesChapter 7 Interfaces 5/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 a
n abstract class:
abstract class className{
…… }
Chapter 7 InterfacesChapter 7 Interfaces 6/44
Inheritance ( 继承 ) Example:
Book
NovelDictionary
Mystery Romance
Chapter 7 InterfacesChapter 7 Interfaces 7/44
Abstract Classes ( 抽象类 )
An abstract class often contains abstract methods, though it doesn’t have to abstract methods consist of only methods declarati
ons, 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.
8
Abstract Classes
abstract class ClassName{
//variables…
abstract dataType MethodName1(); // 抽象方法
… …dataType Method2() {
// method body}
}
已实现的方法,即:非抽象方法
9
//Animal.javapublic 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();}
Chapter 7 InterfacesChapter 7 Interfaces 10/44
Abstract Classes ( 抽象类 )
public class AAnimal // 错误{
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();}
public abstract class AAnimal修改为
Chapter 7 InterfacesChapter 7 Interfaces 11/44
Abstract Classes( 抽象类 )
实例化-由类创建对象 / 实例 . An abstract class cannot be instantiated
( 实例化 ) : objects cannot be created( 对象不能被创建 );
它只能做为父类使用,由它派生的子类必须实现抽象类中所有的抽象方法,才能创建对象。
在 abstract class 中可以有自己的数据成员,也可以有非 abstarct 的成员方法。
Chapter 7 InterfacesChapter 7 Interfaces 12/44
Abstract Class -Example
Shape
Circle Rectangle
Shape is an abstract class.
13
The Shape Abstract Class
• 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.
public abstract class Shape {//method declaration public abstract double area();
public void move() { // non-abstract method // implementation }}
14
The Shape Abstract Class
public Rectangle extends Shape { protected double w, h; public Rectangle() { w = 0.0; h=0.0; }
public double area() { return w * h; }}
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; }…
}
15
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 ( 实例化 ).
16
Example:
//Animal.javapublic 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();
}
17
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); }}
Example: class Dog extends Animal {String type;public Dog() { type=" 宠物狗 ";}public void run(){ }public void cry() { System.out.println (" 汪汪叫 ");}
}
Chapter 7 InterfacesChapter 7 Interfaces 18/44
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 InterfacesChapter 7 Interfaces 19/44
Interface( 接口 ) A Java interface is a collection of constants an
d abstract methods. abstract method: a method header without a metho
d 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( 省略 ).
20
// 格式 : InterfaceName.javainterface InterfaceName {
//Constant/Final Variable Declaration
//Methods Declaration–only method header
}
Printable.java// 接口示例: Printable.javainterface Printable { final int MAX=100;
void add(); float sum(float x,float y);}
Chapter 7 InterfacesChapter 7 Interfaces 21/44
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 InterfacesChapter 7 Interfaces 22/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 interf
aces 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.
23
Defining Interface
class ClassName implements InterfaceName [, InterfaceName2, …]{
// Body of Class}
interface InterfaceName {//Constant/Final Variable Declaration
//Methods Declaration–only method header}
Chapter 7 InterfacesChapter 7 Interfaces 24/44
Interface - Example
speak()
Politician
<<Interface>>Speaker
speak()
Lecturer
speak()
25
class Lecturer implements Speaker {public void speak() { System.out.println(“Talks Object
Oriented Design and Programming!”);
}}
interface Speaker {public void speak( ) ;
}
class Politician implements Speaker {public void speak() {
System.out.println(“Talk politics”);}
}
Speaker.java
Politician.java
Lecturer.java
Chapter 7 InterfacesChapter 7 Interfaces 26/44
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}
27
Interface Inheritance — Example 1
interface L extends J, K { boolean l1();
}
class I implements L { public int j1() { return 4; }
public double k1() { return 6.8; }
public boolean l1() { return true; }
}
interface J { int j = 200; int j1();}
interface K { double k1();}
28
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
29
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.
30
interface I1{ int nValue = 1; void amethod();}
public class A implements I1, I2 { public void amethod() { System.out.println("Hello word!"); } public static void main(String[] args) { A q = new A(); q.amethod();
//Compile Error //System.out.println(q.nValue);
System.out.println(((I1) q).nValue); System.out.println(((I2) q).nValue);
}}
Hello world!12
interface I2 { int nValue = 2; void amethod();}
执行結果 :
31
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;}
32
//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 } }
0110010100
33
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 } }
0110100200
34
Inheritance and Interface Implementation
A general form of interface implementation:
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).
class ClassName extends SuperClass implements InterfaceName […, InterfaceName2, …]{
// Body of Class}
Chapter 7 InterfacesChapter 7 Interfaces 35/44
Example
Abstract class:Shape
Circle Rectangle
Interface:2D-Shape
Abstract class:Shape
Circle Rectangle
Interface:2D-Shape
Abstract class:Shape
Circle Rectangle
Interface:2D-Shape
Abstract class:Shape
Circle Rectangle
Interface:2D-Shape
Abstract class:Shape
Circle Rectangle
Interface:2D-Shape
Abstract class:Shape
Circle Rectangle
Interface:2D-Shape
implements
extends
36
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);
}}
public abstract class Shape { public abstract void setColor(String str); }
interface Shape2D {final double pi = 3.14;public abstract double area();
}
Chapter 7 InterfacesChapter 7 Interfaces 37/44
Reference data types( 引用数据类型 )
The reference( 引用 ) types are 1. class( 类 ) types2. interface ( 接口 ) types3. array( 数组 ) types
Variables of these types can refer to objects( 指向对象 ) of the corresponding type.
38
public class ShapeTest {
public static void main(String[] args) { Shape2D s; // 声明接口的引用数据 s = new Circle(1.0); // 通过实现接口的类创建接口的引用数据 s.area(); // 只能调用接口中定义的方法 //s.setColor(“red”); // 否则,就是语法错误
}
}
39
综合实例 :如何声明和使用以接口和抽象类为类型的数据 (P39-4
2) 。
public abstract class Person {
String name;int age;
{// 初始化块name ="Parent";age = -1;
}
public void initiate(String name, int age){
this.name = name;this.age = age;
}
public void display() {System.out.println(name+","+age);
}
abstract void detailInfo(); }
interface Speaker {public void speak(
);}
Speaker.java
Person.java
40
Politician.javapublic 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"); }
}
41
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");
}
}
42
test.java
public class Test {public static void main(String[ ] args) {
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;person.detailInfo();
}}
43
Java 类实现了一个接口,继承了一个类,如何访问接口与父类中相同的变量 :
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();
}
}
interface Ainterface { int num=1; void method();}
class Aclass {
int num=10;
}
Chapter 7 InterfacesChapter 7 Interfaces 44/44
对象类型转换 Java 中,两个具有继承关系的对象之间可以转换,具体限
制: 两个转换的对象之间应该具有继承关系,也就是说只是在子类和父类
的对象之间进行转换,而不是任意两个类。
一个子类对象的类型可以向上转换成它的父类类型,这个转换过程是安全的。因为父类所具有的信息,子类一般全有。当然,转换过程中会丢失属于子类而不属于父类的信息。
45
对象类型转换 设 A 类是 B 类的父类,用子类 B 创建一个对象,
并把这个对象的引用放到父类的对象中时,如:
称父类对象 a 是子类对象 b 的上转型对象。 对象的上转型对象的实体是子类负责创建的,但上
转型对象会失去原对象的一些属性和功能。
A a;a=new B(); // 上转型对象
A a;B b=new B();a=b; // 上转型对象
46
上转型对象的特点:
•上转型对象不能操作子类新增的成员变量和方法•上转型对象可以操作子类继承或重写的变量和方法•如果子类重写了父类的某个方法,对象上转型对象调用时一定是调用这个重写的方法
对象的上转型对象
子类对象 新增的变量和方法
继承或重写的变量和方法
48
注意:•父类创建的对象和子类对象的上转型对象不是一个含义•可以将对象的上转型对象再强制转换到一个子类对象,这时该子类对象又具备该子类所有的属性和功能。•不可以将父类创建的对象的引用赋值给子类声明的对象。•如果需要把一个父类对象转换成子类类型,则需要强制转换。如: (这样会导致异常)
A a=new A();B b=(B)a;
•类型测试运算符 instanceof 表达式格式:对象引用 instanceof 类名或接口名
49
例(上转型对象、 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 " 一个学生 "; }
}
50
测试: Person.java & Student.javapublic 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
p1=stu1; // 上转
System.out.println(stu1.age); //0System.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); //trueSystem.out.println(p1 instanceof Person); //true
}}
运行结果:truefalse0一个学生 of 一个人0一个学生一个学生truetrue
此语句编译时报错:无
法解析 p1.info ,非法访
问