您的位置:首页 > 编程语言 > Java开发

JAVA构造方法及其重载

2016-11-23 17:49 260 查看
在没有给构造方法的时候,系统会自动给出一个默认的构造方法

但是注意在给出任意一个构造方法的时候,系统将不会提供构造方法

构造方法重载的时候,会根据方法参数来确定使用哪一个构造方法

下面看例子

class Student {
private String name ;
private int age;

public Student() {
System.out.println("这是默认的构造方法");
}

public Student(String name) {
this.name = name;
}

public Student(int age) {
this.age = age;
}

public Student(String name, int age) {
this.age = age;
this.name = name;
}

public void show() {
System.out.println("name: "+name+"----age: "+age);
}
}

class ConstructDemo {
public static void main(String[] args) {
//Student s = new Student();
//System.out.println(s);

Student s0 = new Student();

Student s1 = new Student("刘轲");
s1.show();

Student s2 = new Student(30);
s2.show();

Student s3 = new Student("刘轲",30);
s3.show();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: