目录
1. 总结子类对象实例化的执行顺序2. 举例说明如何实现两个对象之间互发消息。3.谈谈组合与继承的区别以及两者的使用场景?4. Java运行时多态的含义是什么?有什么作用?5. 用接口改写P84例6.8中的程序。6. 简述运算符instanceof的使用场景。
1. 总结子类对象实例化的执行顺序
首先执行父类的构造方法再执行自己的构造方法;首先执行数据成员的默认初始化,static代码块;然后执行初始化字段;最后执行构造方法内部的语句。
2. 举例说明如何实现两个对象之间互发消息。
使用组合的方法,让一个类的对象成为另一个类的数据成员,通过调用其数据据成员相应的方法实现互发消息。
3.谈谈组合与继承的区别以及两者的使用场景?
组合是has-a关系,是指类的某一对象引用作为另一个类的数据成员。继承是is-a关系,指子类扩展或重用父类的方法与域变量,对父类往下进行特化。组合和继承都是重要的代码复用方法。当前设计的类只是使用另一个类已存在的方法或域变量时,选用组合的方法;当前设计的类与另一个类方法与域变量有相似部分时,并且逻辑上当前类是另一个类的特化时,考虑使用继承。
4. Java运行时多态的含义是什么?有什么作用?
运行时多态–百度百科
运行时多态是指,通过继承或实现接口或实现抽象类,通过一个接口,访问不同的类,调用不同的方法。运行时多态是实现代码重用的最强大方法,简化了代码。
5. 用接口改写P84例6.8中的程序。
package Interface
;
import java
.applet
.Applet
;
import java
.awt
.*
;
interface Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
class Rect implements Shape {
public int x
, y
, k
;
public double m
;
public Rect(int x
,int y
,int k
,double m
) {
this.x
= x
;
this.y
= y
;
this.k
= k
;
this.m
= m
;
}
public double getArea() {
return (k
*m
);
}
public double getPerimeter() {
return (2*(x
+y
));
}
}
class Triangle implements Shape {
public int a
, b
, c
;
public double m
;
public Triangle(int a
,int b
,int c
) {
this.a
= a
;
this.b
= b
;
this.c
= c
;
this.m
= (a
+ b
+ c
)/2.0;
}
public double getArea() {
return (Math
.sqrt(m
*(m
-a
)*(m
-b
)*(m
-c
)));
}
public double getPerimeter() {
return (a
+b
+c
);
}
}
class Circle implements Shape {
public int x
, y
, d
;
public double r
;
public Circle(int x
,int y
,int d
) {
this.x
= x
;
this.y
= y
;
this.d
= d
;
this.r
= d
/2.0;
}
public double getArea() {
return (Math
.PI
*r
*r
);
}
public double getPerimeter() {
return (2*Math
.PI
*r
);
}
}
class RunShape extends Applet {
Rect rect
= new Rect(5,15,25,25);
Triangle tri
= new Triangle(5,5,8);
Circle cir
= new Circle(13,90,25);
public void init(){
}
private void drawArea(Graphics g
,Shape s
,int a
,int b
) {
g
.drawString(s
.getClass().getName()+" Area"+s
.getArea(),a
,b
);
}
private void drawPerimeter
(Graphics g
,Shape s
,int a
,int b
) {
g
.drawString(s
.getClass().getName()+" Perimeter"+s
.getPerimeter(),a
,b
);
}
public void paint(Graphics g
) {
g
.drawRect(rect
.x
,rect
.y
,rect
.k
,(int)rect
.m
);
g
.drawString("Rect Area:"+rect
.getArea(),50,35);
g
.drawString("Rect Perimeter:"+rect
.getPerimeter(),50,55);
g
.drawString("Triangle Area:"+tri
.getArea(),50,75);
g
.drawString("Triangle Perimeter:"+tri
.getPerimeter(),50,95);
g
.drawOval(cir
.x
-(int)cir
.d
/2,cir
.y
-(int)cir
.d
/2,cir
.d
,cir
.d
);
g
.drawString("Circle Area:"+cir
.getArea(),50,115);
g
.drawString("Circle Perimeter:"+cir
. getPerimeter(),50,135);
}
}
6. 简述运算符instanceof的使用场景。
a instanceof A a是对象引用,A是类
如果a是A或A的子类的实例化,return true;如果a是A的父类的实例化, return false;如果a与A无关系,则编译不通过。
在实际运用中,instanceof多是与运行时多态相关联使用,如
A a
= new A();
if( a
instanceof B) {
B(a
).getNameB();
} else if( a
instanceof C ) {
C(a
).getNameC();
} else {
System
.out
.println("No name");
}