作者:珍妮20111030 | 来源:互联网 | 2023-05-17 11:57
构造方法1、新建实例时执行的特殊方法newSoldier();newFlashLight():newCar():newDog();新建实例的同时,调用一个构造方法2、一个
构造方法
1、新建实例时执行的特殊方法
new Soldier();
new FlashLight():
new Car():
new Dog();
新建实例的同时,调用一个构造方法
2、一个类必须有构造方法
3、如果不写构造方法,编辑器编译代码时,会默认添加一个构造方法,如下:
public class A(){
public A(){
}
}
4、构造方法重载(具有不同参数)
增加程序的灵活性
public class A(){
public A(int i){
...
}
public A(double d){
...
}
public A(int i,double d){
...
}
}
创建实例时,就不能写new A();
因为已经写了构造参数,运行时就不会再添加默认的构造方法
5、构造方法的作用,通常用来给成员变量赋值
举例1,给Dog类添加构造方法
public class Dog {
public String name;
public int hungry;
public int happy;
public Dog(){
Log.d("Dog","执行了构造方法");
}
public void feed(TextView textView){
if(hungry==0){
textView.setText(name+"吃饱了\n"+textView.getText());
return;
}
hungry-=10;
textView.setText("给"+name+"喂食,hungry:"+hungry+"\n"+textView.getText());
}
......
那么在创建Dog类时,会执行Log输出
举例2,给Dog类添加构造方法
public class Dog {
public String name;
public int hungry;
public int happy;
public Dog(String name,int hungry,int happy){
this.name = name;
this.happy = hungry;
this.happy = happy;
}
......
创建Dog对象的时候写法
dog = new Dog("蠢狗",50,50);
举例3,给Dog类添加构造方法
public class Dog {
public String name;
public int hungry;
public int happy;
public Dog(){
}
public Dog(String name,int hungry,int happy){
this.name = name;
this.happy = hungry;
this.happy = happy;
}
......
创建Dog对象的时候写法有两种
dog = new Dog("蠢狗",50,50);
dog = new Dog();
练习
Student类
public class Student {
public int id;
public String name;
public String gender;
public int age;
public Student(){
}
public Student(int id,String name){
this(id,name,null);
}
public Student(int id,String name,String gender){
this(id,name,gender,0);
}
public Student(int id,String name,String gender,int age){
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
}
public String toString(){
return "\n姓名:"+name+"\n性别"+gender+"\n年龄"+age+"\nid"+id;
}
}
xml
"http://schemas.android.com/apk/res/android"
android:layout_hljs-string">"match_parent"
android:layout_hljs-string">"match_parent"
android:columnCount=
"4" android:orientation=
"vertical" android:rowCount=
"6">