天天看點

無參構造方法

public class Student {

//直接在類中定義:成員變量

//私有屬性 在其他程式裡面不能通路,

private String name;//String 引用類型

private char sex;

private int age;

private String moblie;

//定義一個方法

public Student(){

System.out.println("預設的構造方法");

}

public Student(String _name,char _sex,int _age,String _moblie){

name=_name;

sex=_sex;

age=_age;

moblie=_moblie;

}

public void introduce(){

System.out.println("我的手機号是"+moblie);

System.out.println("我的姓名是"+name);

System.out.println("性别"+sex);

System.out.println("年齡"+age);

}

public void study(){

                System.out.println("我在學習");

}

}

test測試程式

public class Test {

public static void main(String[] args) {

// TODO Auto-generated method stub

//構造方法,使用new關鍵字建立一個對象(執行個體化對象)

Student stu1 = new Student("張三",'男',23,"135846795");

//通路對象的方法:對象.方法名

stu1.introduce();

Student stu2= new Student("李四",'男',22,"159978563");

stu2.introduce();

Student stu3 =new Student();

stu3.introduce();

}

}

繼續閱讀