1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Person { private int age = 10; public Person(){ System.out.println("初始化年龄:"+age); } public int GetAge(int age){ this.age = age; return this.age; } } public class test1 { public static void main(String[] args) { Person Harry = new Person(); System.out.println("Harry's age is "+Harry.GetAge(12)); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Country { String name; void value() { name = "China"; } } class City extends Country { String name; void value() { name = "Shanghai"; super.value(); //调用父类的方法 System.out.println(name); System.out.println(super.name); } public static void main(String[] args) { City c=new City(); c.value(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Person { public static void prt(String s) { System.out.println(s); } Person() { prt("父类·无参数构造方法: "+"A Person."); }//构造方法(1) Person(String name) { prt("父类·含一个参数的构造方法: "+"A person's name is " + name); }//构造方法(2) } public class Chinese extends Person { Chinese() { super(); // 调用父类构造方法(1) prt("子类·调用父类”无参数构造方法“: "+"A chinese coder."); } Chinese(String name) { super(name);// 调用父类具有相同形参的构造方法(2) prt("子类·调用父类”含一个参数的构造方法“: "+"his name is " + name); } Chinese(String name, int age) { this(name);// 调用具有相同形参的构造方法(3) prt("子类:调用子类具有相同形参的构造方法:his age is " + age); } public static void main(String[] args) { Chinese cn = new Chinese(); cn = new Chinese("codersai"); cn = new Chinese("codersai", 18); } } |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |