标签:
package com.liaojianya.chapter1; /** * This program demonstrates the correct use of construct overload. * @author LIAO JIANYA * 2016年7月21日 */ public class ConstructOverload { public static void main(String[] args) { Person2 p = new Person2(); Person2 p1 = new Person2(33); Person2 p2 = new Person2("wangxiaoyuan", 23); p.talk(); p1.talk(); p2.talk(); } } class Person2 { private String name; private int age; public Person2() { name = "zhangsan"; age = 22; } public Person2(int age) { name = "wangyuan"; this.age = age; } public Person2(String name, int age) { this.name = name; this.age = age; } public void talk() { System.out.println("My name is " + name + ", I am " + age + " years old."); } }
运行结果:
My name is zhangsan, I am 22 years old. My name is wangyuan, I am 33 years old. My name is wangxiaoyuan, I am 23 years old.
分析:1、第一个构造方法是无参构造,第二个,第三个是有参构造,当对象实例化时,根据new出来对象中是否无参还是有参以及参数个数来调用对应的构造方法。
2、三个构造方法形成了构造方法的重载。
标签:
原文地址:http://www.cnblogs.com/Andya/p/5692906.html