Ball ball = new Ball("Football");
这样就没有异常了,在用变量之前必须先声明,否则,会报异常。在Rollable接口中使用的定义的ball的变量。
interface Playable {
void play();
}
interface Bounceable {
void play();
}
interface Rollable extends Playable, Bounceable {
public Ball ball = new Ball("PingPang");
}
abstract class Rollable2 implements Playable,Bounceable{
public static Ball ball = new Ball("PingPang");
// public void play(){
// System.out.println("abstract Rollable2");
// }
}
class Ball extends Rollable2 {
public static void main(String[] args){
Rollable2 ball =new Ball("lii");
ball.play();
}
private String name;
public String getName() {
return name;
}
public Ball(String name) {
this.name = name;
}
public void play() {
Ball ball2=new Ball("Football");
System.out.println(Rollable2.ball.getName());
Rollable2.ball = ball2;
System.out.println(Rollable2.ball.getName());
}
}
通过测试抽象方法的成员变量,可以被访问改变,但是接口中的成员变量不能被直接赋值,因为接口的默认的修饰符是public final,即使不被修饰,也会自动加上。 |