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

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

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();
    }
}

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

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();//匿名对象调用
    }
}

猜你喜欢

转载自blog.csdn.net/guxunshe5199/article/details/81104653
今日推荐