Java陷阱一箩筐 --- 第一日: 类与访问控制
1.
abstract class Name {
private String name;
public abstract boolean isStupidName(String name) {}
}
大侠们,这有何错误?
2.
public class Something {
void doSomething () {
private String s = "";
int l = s.length();
}
}
有错吗?
3.
abstract class Something {
private abstract String doSomething ();
}
这好像没什么错吧?
4.
public class Something {
public int addOne(final int x) {
return ++x;
}
}
这个比较明显。
5.
public class Something {
public static void main(String[] args) {
Other o = new Other();
new Something().addOne(o);
}
public void addOne(final Other o) {
o.i++;
}
}
class Other {
public int i;
}
和上面的很相似,都是关于final的问题,这有错吗?
6.
class Something {
int i;
public void doSomething() {
System.out.println("i = " + i);
}
}
有什么错呢? 看不出来啊。
7.
class Something {
final int i;
public void doSomething() {
System.out.println("i = " + i);
}
}
和上面一题只有一个地方不同,就是多了一个final。这难道就错了吗?
8.
public class Something {
public static void main(String[] args) {
Something s = new Something();
System.out.println("s.doSomething() returns " + doSomething());
}
public String doSomething() {
return "Do something ...";
}
}
看上去很完美。
9.
此处,Something类的文件名叫OtherThing.java
class Something {
private static void main(String[] something_to_do) {
System.out.println("Do something ...");
}
}
这个好像很明显。
10.
今天最难的一题:
interface Playable {
void play();
}
interface Bounceable {
void play();
}
interface Rollable extends Playable, Bounceable {
Ball ball = new Ball("PingPang");
}
class Ball implements Rollable {
private String name;
public String getName() {
return name;
}
public Ball(String name) {
this.name = name;
}
public void play() {
ball = new Ball("Football");
System.out.println(ball.getName());
}
}
这个错误不容易发现。