JAvaマルチステートトラップ
もとのように、まずみんなを試験して、運行しない情況の下で次のプログラムの出力の結果を言い出します(先にこれが多態についてのことに注意してください)
以上はいずれも最近Thinking in Javaを読んで得たものです
package acm;
//
class Test extends Main {
private void write() {
System.out.println("Test");
}
}
public class Main {
private void write() {
System.out.println("Main");
}
public static void main(String[] args) {
Main main = new Test();
main.write();
}
}
// Test, private final 。 。
// ,Test write ,Main ,
// private 。 :Main
//
class Super {
public int field = 0;
public int getField() {
return field;
}
}
class Sub extends Super {
public int field = 1;
public int getField() {
return field;
}
public int getSuperField() {
return super.field;
}
}
public class Main {
public static void main(String[] args) {
Super sup = new Sub();
System.out.println("sup.field= " + sup.field + ",sup.getField()="
+ sup.getField());
Sub sub = new Sub();
System.out.println("sub.field= " + sub.field + ",sub.getField()="
+ sub.getField() + ",sub.getSuperField()="
+ sub.getSuperField());
}
}
// Sub Super , , 。
// , Super.field Sub.field 。 ,Sub field :
// Super 。 :
//sup.field= 0,sup.getField()=1
//sub.field= 1,sub.getField()=1,sub.getSuperField()=0
//
class Glyph {
void draw() {
System.out.println("Glyph.draw()");
}
Glyph() {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
private int radius = 1;
RoundGlyph(int r) {
radius = r;
System.out.println("RoundGlyph.RoundGlyph(),radius=" + radius);
}
void draw() {
System.out.println("RoundGlyph.draw(),radius=" + radius);
}
}
public class Main {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
// Glyph draw() ,radius 1, 0。
// , :
//(1) , 。
//(2) 。 , draw() ( RoundGlyph ),
// radius 0, (1) 。
//(3) 。
//(4) 。
// :
//Glyph() before draw()
// RoundGlyph.draw(),radius=0
// Glyph() after draw()
// RoundGlyph.RoundGlyph(),radius=5
以上はいずれも最近Thinking in Javaを読んで得たものです