面向对象
1.什么是类?什么是对象?
面向对象(Object-Oriented)是一种编程范式或思想方式,它将程序中的数据和功能封装成对象,并通过对象之间的交互来实现程序的设计和开发。在面向对象编程中,程序主要由对象组成,每个对象都有自己的状态(属性)和行为(方法)。对象之间可以通过消息传递来进行通信和交互,从而实现数据的共享与协作。
- 现实生活就是有很多对象组成,基于对象抽出了类
- 对象:软件中真实存在的单个的个体
- 类 :类型/类别,代表一类个体
- 类是对象的模板,对象是类的具体实例,可以将类理解为类别/模子/图纸
- 类中可以包含:
对象的属性/特征/数据------------------成员变量
对象的行为/动作/功能------------------方法
2.如何创建类?如何创建对象?如何访问成员?
以下十个简单例子
public class Student {
//成员变量---描述对象的属性
String name;
int age;
String className;
String stuId;
//方法------描述对象的行为
void study(){
System.out.println(name+"在学习...");
}
void sayHi(){
System.out.println("大家好,我叫"+this.name+",今年"+this.age+"岁了,所在班级为"+this.className+",学号为:"+this.stuId);
}
void playWith(String anotherName){
System.out.println(this.name+"正在和"+anotherName+"一起玩...");
}
}
public class StudentTest {
public static void main(String[] args) {
//创建一个学生对象
Student zs = new Student();
//访问成员变量
zs.name = "张三";
zs.age = 24;
zs.className = "jsd2302";
zs.stuId = "001";
//调用方法
zs.study();
zs.sayHi();
zs.playWith("李四");
Student ls = new Student();
ls.name = "李四";
ls.age = 25;
ls.className = "jsd2302";
ls.stuId = "002";
ls.study();
ls.sayHi();
ls.playWith("张三");
//1)创建了一个学生对象
//2)给所有成员变量赋默认值
Student ww = new Student();
ww.study();
ww.sayHi();
ww.playWith("张三");
}
}
3.this
- 指代当前对象,哪个对象调用方法它指的就是那个对象
- this只能用在方法中,方法中访问成员变量之前默认有个this
- this的用法:
this.成员变量名---------------访问成员变量
当成员变量与局部变量同名时,若想访问成员变量,则this不能省略
this.方法名()--------------------调用方法
this()------------------------------调用构造方法
4.构造方法:构造函数,构造器,构建起
- 给成员变量赋初始值
- 语法:与类同名,没有返回值类型(连void都没有)
- 调用:在创建(new) 对象时自动被调用
- 若自己不屑构造方法,则编译器默认提供一个无参构造方法,若自己写了,则不再默认提供
- 构造方法可以重载
public class Student {
//成员变量---描述对象的属性
String name;
int age;
String className;
String stuId;
//构造方法
Student(){
this("无名氏",1,"未知","未知"); //调用4个参数构造
}
Student(String name,int age,String className,String stuId){
this.name = name;
this.age = age;
this.className = className;
this.stuId = stuId;
}