Java-SCJP question
Consider:
class Building {
Building() {
System.out.print("b ");
}
Building(String name) {
this();
System.out.print("bn "+name);
}
}
public class House extends Building {
House() {
System.out.print("h ");
}
House(String name) {
this();
System.out.print("hn "+name);
}
public static void main(String a[]) {
new House("x ");
}
}
For the above program, I thought the output must be h hn x. But the output comes as b h hn x.
Why?
Later
public class TestDays {
public enum Days {
MON,TUE,WED
};
public static void main(String []args) {
for(Days d : Days.values())
;
Days [] d2=Days.values();
System.out.println(d2[2]);
}
}
I can't understand the above program. Please help me.
class Mammal {
String name="furry";
String makeNoise() {
return "generic noise";
}
}
class Zebra extends Mammal {
String name="stripes";
String开发者_如何学Go makeNoise() {
return "bray";
}
}
public class ZooKeeper {
public static void main(String args[]) {
new ZooKeeper().go();
}
void go() {
Mammal m=new Zebra();
System.out.println(m.name+m.makeNoise());
}
}
In the above program, makeNoise() is overridden. And so output must be stripes bray. But the output is furry bray.
Problem 1:
I thought the output must be h hn x. But the output comes as b h hn x.
You are missing the fact that the House()
constructor implicitly invokes the no-args constructor of Building
.
Problem 2:
I cant understand the above program. Please help me.
It is printing the 3rd value of the enumeration. The empty for-loop looks a bit strange, but I suspect that's just a typing error. If there is something else you don't understand, you'll have to say what it is. (I left my mind-reading helmet at home ... and Jon Skeet is asleep.)
Problem 3:
In the above program, makeNoise() is overridden. And so output must be stripes bray. But the output is furry bray.
The reason you are seeing "furry" instead of "stripes" is that attributes of a class are NOT overridden. A Zebra instance actually has two fields called name
, and your code binds to one or the other depending on the declared type of the reference variable. In this case, the declared type of m
is Mammal
so you are getting the mammal version of the name.
1.- b appears first because this code:
House() {
System.out.print("h ");
}
First call the super class no args constructor ( that's done by the compiler ) so you should think about it as:
House() {
super();
System.out.print("h ");
}
2- Your're declaring a Java enum
The for loop iterates all the possible values ( MON, TUE, WED )
for(Days d : Days.values())
;
But, it doesn't do anything ( see the ; that means "nothing" )
And then, creates an array with those values
Days [] d2=Days.values();
To finally print the 3rd position ( arrays in Java are zero based, so 0-1-2 is the 3rd position )
System.out.println(d2[2]);
Which prints WED
3.- See Stephen C answer. You're getting the super class attribute.
精彩评论