对象和类的关系:有一个学生 ,需要在表格上填写自己的信息 ,那么这个打印机就像一个类 ,打印出的表格就是一个对象,用类创建对象,学生填的信息 ,就是我所初始化的信息。
类的组成:由 属性(也叫成员变量)和方法组成,如果单单只有一个属性 ,那类就像是一个结构体。
public class SxStu {/*创建一个学生信息的类*/
int id;
String name;/*成员变量 ,类的属性*/
Computer comp;/*定义一个computer 成员变量 */
void study() {/*类的 方法*/
System.out.println("正在学习!用的电脑:"+comp.brand);
}
void play() {
System.out.println("正在玩游戏");
}
public static void main(String[] args) {
SxStu stu = new SxStu();
Computer c1 = new Computer();/*创建一个对象*/
c1.brand="联想小新潮";/*在模板里添加修饰*/
stu.id = 0001;
stu.name = "姚景阳";
stu.comp = c1;
stu.play();
stu.study();
}
}
class Computer{/*可以创建多个类 ,但只有一个public类*/
String brand;/*成员变量 ,也叫类的属性*/
}