注意父子类的初始化顺序也~~~还有,MAIN函数在哪个类里,就用哪个类来命名文件:
代码:
1 class Parent { 2 private int num = 1; 3 public Parent() { 4 System.out.println("Now,initial parent calss."); 5 } 6 public void test() { 7 System.out.println("This is the parent's test method."); 8 } 9 } 10 11 public class ParentTest extends Parent { 12 private String name; 13 private int age; 14 public ParentTest() { 15 name = "Sky"; 16 age = 20; 17 } 18 public static void main(String[] args) { 19 ParentTest t = new ParentTest(); 20 t.test(); 21 System.out.println(t.name + "'s age is :" + t.age); 22 } 23 }
结果:
D:\javacode>javac ParentTest.java
D:\javacode>java ParentTest
Now,initial parent calss.
This is the parent's test method.
Sky's age is :20
时间: 2024-09-18 14:57:44