版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
Java学习第一次课-----类与对象
首先,关于类与对象的定义
------类:一些具有相同属性,行为方法,功能的对象的模板。 例如一张椅子,一个人,一瓶水……
------对象:一个具体的事物 例如:学生,老师,电脑,游戏等等。
------属性与方法:对象都有大小,形状,颜色等等特征,这称之为属性,他们的动作,比如学习,运动,玩游戏等等,称之为方法(一般静物不考虑方法)。
PS:类名首字母大写(Java大小写敏感,Hello!=hello)
创建一个源文件—.java后缀的文件
------创建一个类()
------关键字:class(类的标识词)
------格式:pubilc(访问修饰符)class 类名{}
------属性:写在类中
------格式:public 属性类型 属性变量名=属性初始值;int x;
------方法:写在类中
------格式:public 返回值类型void 方法名(参数类型 参数变量名){x=200; return返回值;}
------程序的启动
------程序入口 主函数 主方法
------public static void main(String[] args){ }
------输出语句
------System.out.print();
------要换行的话就是 System.out.println();
------类创建一个对象的过程:实例化一个对象
------格式:类名 对象变量名 = new 类名();
来个实例
我们写一个学生类
–(先在file里new一个package,然后在package里new一个class)
------学生类里有很多学生(student123)
------属于学生的属性(名字,学校,学号,学分)
------属于学生的方法(学习,获得学分)
package com.zyz0928;
public class Student {
//属于学生的属性
String name;
String school;
int stuid;
int score;
// 属于学生的方法
public void study() {
System.out.println("来自"+school+name+"学分:"+score+" 学号:"+stuid);
int addscore=3;
score=score+addscore;
System.out.println("来自"+school+name+"学习了一次,学分增加了"+addscore+"分");
}
//程序入口
public static void main(String[] args) {
//创建一个具体的学生
Student stu1 = new Student();
stu1.name = "wry";
stu1.school = "CSU";
stu1.stuid=190812;
stu1.score=0;
stu1.study();//调用方法
Student stu2 = new Student();
stu2.name = "zyz";
stu2.school ="CSU";
stu2.stuid=191328;
stu2.score=0;
stu2.study();
Student stu3 = new Student();
stu3.name = "wy";
stu3.school ="CSU";
stu3.stuid =191331;
stu3.score =6;
stu3.study();
}
}