Super 程序题

题目一

  1. class Base{
  2. Base(){
  3. System.out.println("Base");
  4. }
  5. }
  6. public class Checket extends Base{
  7. Checket(){
  8. System.out.println("Checket");
  9. super();
  10. }
  11. public static void main(String argv[]){
  12. Checket a = new Checket();
  13. }
  14. }

输出是什么? 是 compile time error. super() 必须放在前面.

放在前面之后,输出为 Base Checket

题目二

  1. import java.util.Date;
  2. public class Test extends Date{
  3. public static void main(String[] args) {
  4. new Test().test();
  5. }
  6. public void test(){
  7. System.out.println(super.getClass().getName());
  8. }
  9. }

返回的结果是 Test

因为super.getClass().getName() 调用了父类的 getClass() 方法, 返回当前类

如果想得到父类的名称,应该用如下代码:

  1. getClass().getSuperClass().getName()

题目三

  1. public abstract class Car {
  2. String name = "Car";
  3. public String getName(){
  4. return name;
  5. }
  6. public abstract void demarre();
  7. }
  8. public class B extends Car{
  9. String name = "B";
  10. public String getName(){
  11. return name;
  12. }
  13. public void demarre() {
  14. System.out.println(getName() + " demarre");
  15. }
  16. }
  17. public class C extends B{
  18. String name = "C";
  19. public String getName(){
  20. return name;
  21. }
  22. public void demarreWithSuper() {
  23. System.out.println(super.getName() + " demarre");
  24. }
  25. public void demarreNoSuper() {
  26. System.out.println(getName() + " demarre");
  27. }
  28. }
  29. public class D extends B{
  30. public String getName(){
  31. return name;
  32. }
  33. public void demarreNoSuper() {
  34. System.out.println(getName() + " demarre");
  35. }
  36. }
  37. public class Test {
  38. public static void main(String[] args) {
  39. B b = new B();
  40. b.demarre();
  41. Car bCar = new B();
  42. bCar.demarre();
  43. C c = new C();
  44. c.demarre(); // c 里并没有定义这个函数
  45. c.demarreWithSuper();
  46. c.demarreNoSuper();
  47. D d = new D();
  48. d.demarre();
  49. transfer(c); // TransferC
  50. transfer((B)c); // TransferB
  51. transfer(d); // TransferB
  52. }
  53. public static void transfer(B b){
  54. System.out.println("TransferB");
  55. b.demarre();
  56. }
  57. public static void transfer(C c){
  58. System.out.println("TransferC");
  59. c.demarre();
  60. }
  61. }
  62. }

输出是
B demarre
B demarre
C demarre
B demarre
C demarre
B demarre
TransferC
C demarre
TransferB
C demarre
TransferB
B demarre