目录
一 . 面对对象概述
面对对象三大特征:封装,继承,多态
核心思想:
-
封装(Encapsulation)
-
继承(Inheritance)
-
多态(Polymorphism)
-
抽象(Abstraction)
特点:
-
以对象为基本单位,对象是类的实例。
-
通过类定义对象的属性(成员变量)和行为(方法)。
二 . 类与对象
1.类
-
对象的模板,定义对象的属性和方法。
class Student{
// 这是一个类
}
2.对象
-
类的具体实例。
Student s = new Student();
三 . 成员属性封装
1. 封装原则
- 使用
private修饰属性,禁止外部直接访问。
(博哥有话说:使用什么修饰符具体看需要什么,一共有四种修饰符private,default,protected,public)
- 通过
getter/setter方法控制访问。
class Student {
private String name; // 私有属性
private int age;
// Getter/Setter 方法
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
四 . 构造方法
(博哥有话说:无参构造和有参构造是一种典型的的方法重载)
1.无参构造
-
默认存在(若未定义任何构造方法)。
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
}
}
class Student{
private String name;
private int age;
private String address;
private String phone;
public Student() {
//无参构造
}
}
2.有参构造
-
用于初始化对象属性。
public class Main {
public static void main(String[] args) {
Student s2 = new Student("张三", 18, "北京", "13888888888");
}
}
class Student{
private String name;
private int age;
private String address;
private String phone;
public Student(String name, int age, String address, String phone) {
//有参构造
}
}
五 . 匿名对象
-
没有变量引用的对象,用完即弃。
-
适用场景:只需调用一次方法时。
new Student().setName("张三"); // 匿名对象
六 . this关键字
(博哥有话说:在未来的学习中,会大量使用到this关键字)
-
作用:
-
指代当前对象的成员变量(解决局部变量与成员变量同名冲突)。
-
调用当前类的其他构造方法(
this())。
-
public Student(String name) {
this.name = name; // this 指代成员变量
}
七 . 简单的Java类
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("张三", 18, "北京", "13888888888");
}
}
// 学生类
class Student{
private String name;
private int age;
private String address;
private String phone;
public Student() {
//无参构造
}
public Student(String name, int age, String address, String phone) {
//有参构造
this.name = name;
this.age = age;
this.address = address;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
八 . static关键字
1. 静态变量
-
属于类,所有对象共享。
class Student {
static String school = "大学"; // 静态变量
}
2. 静态方法
-
可直接通过类名调用(无需创建对象)。
-
限制:不能访问非静态成员。
class MathUtils {
static int add(int a, int b) { return a + b; }
}
// 调用:MathUtils.add(1, 2);
3. 静态代码块
-
类加载时执行,用于初始化静态资源。
static {
System.out.println("静态代码块执行");
}
九 . 代码块
(博哥有话说:我们未来写的代码多是普通代码块)
1. 普通代码块
-
在方法中定义,控制变量作用域。
void demo() { { int x = 10; } // 普通代码块 // x 在此处不可见 }
2. 构造代码块
-
在类中定义,每次创建对象时执行(优先于构造方法)。
class Student { { System.out.println("构造代码块"); } }
3. 执行顺序
静态代码块 → 构造代码块 → 构造方法

被折叠的 条评论
为什么被折叠?



