java基础 第七章 上(对象类型例题)
1.class Init{
int num; //成员变量有默认初始化,所以不需要给初始值。
}
public class InitDemo{
public static void main(String[] args){
Init s = new Init();
int age = 0; //如果定义方式为 int age ; 则报错(局部变量未初始化),因为局部变量没有默认初始化。
System.out.println(s.num); //输出 0;
}
}
2.class Student{
int id;
int age;
}
import java.util.*;
public class StudentManager{
public static void main(String[] args){
Student student1 = new Student();
Student student2 = new Student();
setVar(student1);
setVar(student2);
}
}
static void setVar(student){
Scanner in = new Scanner(System.in);
student.id = in.nextInt();
student.age = in.nextInt();
System.out.println(student.id);
System.out.println(student.age);
}
3.public class demo1{
public static void main(String[] args){
int x = 3;
show(x);
System.out.println(x); //输出 3;
}
static void show(int x){
x = 4
}
}
4.class demo2{
int x = 3;
}
public class text{
show(demo2 d){
d.x = 4;
}
public static void main(String[] args){
demo2 d = new demo2;
d.x = 9;
System.out.println(d.x); //输出9
show(d);
System.out.println(d.x);//输出4
}
}
5. class demo3{
int x = 1;
show(){
int x = 2;
System.out.println(x);//输出2
}
}
public class demoText{
public static void main(String[] args){
demo3 d = new demo3();
d.show();
System.out.println(d.x);//输出 1
}
}