/**
- 构造方法
*默认的构造方法有没有修饰符和定义的类有关
*/
class T1{
//默认构造方法 类是缺省的,默认构造方法就是缺省的
T1(){
}
public class test {
//默认构造方法 类是public 默认构造方法就是public
public test(){
}
}
/**
* 如果显示的定义了构造方法那么就会使用显示的构造
*/
public Test1(){
age=1;
name="zhangsan";
}
public int age;
public String name;
public void showInfo(){
System.out.println(age);
System.out.println(name);
}
public static void main(String[] args) {
Test1 t=new Test1();
t.showInfo();
}
/**
* 构造方法可以写带参数的构造
* @param a
* @param n
*/
public Test1(int a,String n){
age=a;
name=n;
}
public int age;
public String name;
public void showInfo(){
System.out.println(age);
System.out.println(name);
}
public static void main(String[] args) {
Test1 t=new Test1(1,"ZHANGSAN"); //new 对象实际上就是调用类的构造方法
t.showInfo();
}
练习:
/**
- 1.在前面定义的类中添加构造器,利用构造器设置所有的age属性,初始值为18,
- 2.修改上题中的类和构造器增加name属性,使得每次创立对象的同时初始化对象的age属性和name属性值。
/
public class Test2 {
/*
-
1.在前面定义的类中添加构造器,利用构造器设置所有的age属性,初始值为18,
*/
public Test2(){
age=18;
}
public int age;public void showInfo(){
System.out.println(age);
}public static void main(String[] args) {
扫描二维码关注公众号,回复: 9314093 查看本文章Test2 t=new Test2(); t.showInfo();
}
/**
* 2.修改上题中的类和构造器增加name属性,使得每次创立对象的同时初始化对象的age属性和name属性值。
*/
public Test2(int a,String n){
age=a;
name=n;
}
public int age;
public String name;
public static void main(String[] args) {
Test2 t=new Test2(22,"zhangsan");
System.out.println(t.age);
System.out.println(t.name);
}
}