java什么是“类与对象”
一、概念简述
java代码是以类为单位的,类包含了一些具体事物(对象)的属性和行为方式。
对象是相对抽象的类的具体,我甚至把它看作是类的一个小子集,使用的时候就是在你需要用到的类下创建(“new一下”)一个对象来调用里面的属性或行为。
二、运用步骤
首先明确一下我创建了两个类:
①StudentAction(用来保存学生行为的属性和规则)
②Manager(用来执行调用)
tep1在①中创建属性和行为
public class StudentAction {
private String name;//学生属性
private int score=0;
//获取学生名行为
public void SetName(String n) {
name=n;
}
//学生学习行为
public void study() {
score++;
System.out.println(name+"同学正在学习,学分+1");
}
//学生游戏行为
public void play() {
score--;
System.out.println(name+"同学正在玩耍,学分-1");
}
//显示学分行为
public void showscore() {
System.out.println("目前学分是"+score);
if(score>=5) {
System.out.println("学分已修够!");
}else {
System.out.println("学分未修够!");
}
}
}
在②中创建对象执行①中的行为
public class Manager {
public static void main(String args[]) {
StudentAction st1=new StudentAction();
st1.SetName("巴卡巴卡");
for(int i=0;i<6;i++) {
st1.study();
}
st1.play();
st1.showscore();
}
}
运行结果