java 构造函数
import java.util.Scanner;
import java.util.Arrays;
class m{
String str;
int x;
}
public class Main{
public static void main(String[] args){
m s1 = new m();
m s2 = new m();
s1.str = "abc"; //重复的初始化流程
s1.x = 1;
s2.str = "dec";
s2.x = 2;
System.out.println(s1.str+" "+s1.x);
}
}
使用构造函数避免重复流程:
import java.util.Scanner;
import java.util.Arrays;
class m{
String str;
int x;
m(String str,int x){ //构造函数,与类名称相同
this.str = str; //this 指定哪个对象
this.x = x;
}
}
public class Main{
public static void main(String[] args){
m s1 = new m("abc",1); //直接
m s2 = new m("dec",2);
System.out.println(s1.str+" "+s1.x);
}
}
使用数组创建多个对象
import java.util.Scanner;
import java.util.Arrays;
class m{
String str;
int x;
m(String str,int x){
this.str = str;
this.x = x;
}
}
public class Main{
public static void main(String[] args){
m[] s={new m("abc",123),
new m("dec",234),
new m("sds",345)};
for (m t : s)
System.out.println(t.str+" "+t.x);
}
}
还没有评论,来说两句吧...