目录
1.什么是类?
类:是一组相关属性和行为的集合。
属性:就是该事物的状态信息。
行为:就是该事物能够做什么。
例如:小猫
属性:名字,年龄,颜色。
行为:叫,跑,走。
2.什么是对象?
对象:是一类事物的具体体现。对象是类的实例,具备该类事物的属性和行为。
例如:一只小猫
属性:Tom,2,yellow。
行为:溜墙根走、蹦跶的跑、喵喵叫。
3.类和对象的关系
-
类是一类事物的描述,是抽象的。
-
对象是一类事物的实例,是具体的。
-
类是对象的模板,对象是类的实体,比如:类是盖房子的图纸,对象就是一座座根据图纸改出来的房子。
4.类的定义
类的定义格式:
public class ClassName{
//成员变量
//成员方法
}
代码示例:
public class Student {
//成员变量
String name;
int age;
//成员方法
public void study() {//不需要ststic修饰
System.out.println("好好学习");
}
public void eat() {
System.out.println("吃饭");
}
}
5.对象的使用
5.1创建格式:
类名 对象名 = new 类名( );
5.2使用对象访问成员变量:
对象名.成员变量;
对象名.成员方法;
代码示例:
public class Test_Student {
public static void main(String[] args) {
Student student = new Student();
System.out.println(student);//地址值
System.out.println("姓名:" + student.name);//null
System.out.println("年龄:" + student.age);//0
System.out.println("---------------");
student.name = "张三";
student.age = 12;
System.out.println("姓名:" + student.name);//姓名:张三
System.out.println("年龄:" + student.age);//年龄:12
System.out.println("---------------");
student.eat();//吃饭
student.study();//好好学习
}
}
5.3 一个对象的内存图
5.4 使用对象类型作为方法的参数
public class Test_Student {
public static void main(String[] args) {
Student student = new Student();
student.name = "张三";
student.age = 12;
method(student);//使用对象类型作为方法的参数
}
public static void method(Student student) {
System.out.println(student.name);
System.out.println(student.age);
}
}
5.5 使用对象类型作为方法的返回值
public static void main(String[] args) {
Student student = getStudent();//地址值0x100
System.out.println(student.age);
System.out.println(student.name);
}
public static Student getStudent() {
Student student1 = new Student();//假设地址值为0x100
student1.name = "李娜";
student1.age = 13;
return student1;//返回地址值0x100
}
6.成员变量和局部变量的区别
局部变量(方法中用) | 成员变量(类中用) | |
定义的位置不同 | 在方法内部 | 在方法外部,直接写在类中 |
作用范围不同 | 只有在方法中可以用 | 整个类中都可以用 |
默认值不一样 | 没有默认值,必须先定义,赋值,在使用(必须赋值) | 如果没有赋值,会有默认值(可以不赋值) |
内存位置不一样 | 在栈中 | 在堆中 |
生命周期不一样 | 随着方法的调用而存在,随着方法的调用完毕而消失 | 随着对象的创建而存在,随着对象的消失而消失 |