您的位置:首页 > 其它

第二章02 构造方法与匿名对象

2018-07-18 20:37 113 查看

构造方法:方法名称与类名称相同,且无返回值;
                  不定义构造方法时,系统默认有一个无参构造方法;
                   包括 有参构造 与 无参构造。
                    构造方法例子如下:                                

[code]class Student{
private String name;
private int age;
public Student(){} //无参构造方法
public Student(String n, int a){//有参构造方法
name = n;
age = a;
}
public setName(String n){
name = n;
}
public setAge(int a){
age = a;
}
public void tell(){
System.out.println("姓名:"+name+"年龄:"+age);
}
}
public class mainDemo{
public static void main(String args[]){
//调用无参构造
Student stu = new Student();
stu.setName("李明");
stu.setAge(10);
//调用有参构造
Student stu = new Student("李明",10);
//上述2种调用方式,任意选择一种
stu.tell();
}
}

匿名对象:无名对象。如下代码所示:

[code]class Student{
private String name;
private int age;
public Student(){} //无参构造方法
public Student(String n, int a){//有参构造方法
name = n;
age = a;
}
public setName(String n){
name = n;
}
public setAge(int a){
age = a;
}
public void tell(){
System.out.println("姓名:"+name+"年龄:"+age);
}
}
public class mainDemo{
public static void main(String args[]){
new Student("李明",10).tell();//匿名对象调用
}
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐