Java面向对象基础实例详解
面向对象编程是Java的灵魂,理解类与对象就是理解Java的世界观。
1. 面向对象编程思想
1.1 什么是面向对象?
面向对象是一种编程思想,它将现实世界的事物抽象为程序中的对象。每个对象都有:
- 属性(Attribute):描述对象的状态
- 方法(Method):描述对象的行为
类比理解:
- 类(Class):相当于"图纸"或"模板",定义了对象应该有什么属性和方法
- 对象(Object):相当于"实物",根据图纸创建出来的具体实例
举例:
- "人"是一个类,"张三"是一个对象
- "汽车"是一个类,"我的车"是一个对象
- "银行账户"是一个类,"我的储蓄账户"是一个对象
2. 定义类
2.1 类的基本结构
public class Person {
// 属性(成员变量)
String name;
int age;
String gender;
// 方法(成员方法)
void introduce() {
System.out.println("大家好,我叫" + name + ",今年" + age + "岁。");
}
void eat() {
System.out.println(name + "正在吃饭。");
}
void sleep() {
System.out.println(name + "正在睡觉。");
}
}2.2 成员变量 vs 局部变量
public class VariableScope {
// 成员变量:定义在类中,整个类都能访问
String memberVar = "我是成员变量";
void testMethod() {
// 局部变量:定义在方法中,只在方法内有效
String localVar = "我是局部变量";
System.out.println(memberVar); // 可以访问
System.out.println(localVar); // 可以访问
}
void anotherMethod() {
System.out.println(memberVar); // 可以访问
// System.out.println(localVar); // 编译错误!无法访问
}
}3. 创建和使用对象
3.1 实例化对象
使用 new 关键字创建对象:
public class ObjectDemo {
public static void main(String[] args) {
// 创建Person对象
Person person1 = new Person();
person1.name = "张三";
person1.age = 20;
person1.gender = "男";
// 调用对象的方法
person1.introduce(); // 大家好,我叫张三,今年20岁。
person1.eat(); // 张三正在吃饭。
// 创建第二个对象
Person person2 = new Person();
person2.name = "李四";
person2.age = 22;
person2.gender = "女";
person2.introduce(); // 大家好,我叫李四,今年22岁。
}
}4. 构造函数
构造函数是对象创建时自动调用的特殊方法,用于初始化对象。
4.1 默认构造函数
如果不写构造函数,Java会自动提供一个无参构造函数:
public class Student {
String name;
int age;
// 如果不写任何构造函数,Java自动提供:
// public Student() {}
}4.2 自定义构造函数
public class Student {
String name;
int age;
String school;
// 无参构造函数
public Student() {
System.out.println("创建了一个学生对象");
}
// 带参数的构造函数
public Student(String name, int age, String school) {
this.name = name;
this.age = age;
this.school = school;
}
// 部分参数的构造函数
public Student(String name, int age) {
this.name = name;
this.age = age;
this.school = "未知学校";
}
void introduce() {
System.out.println("我叫" + name + ",今年" + age + "岁,在" + school + "上学。");
}
}4.3 构造函数重载
同一个类可以有多个构造函数,参数不同:
public class ConstructorOverloadDemo {
public static void main(String[] args) {
// 使用无参构造函数
Student s1 = new Student();
s1.introduce(); // 输出默认值
// 使用全参构造函数
Student s2 = new Student("张三", 18, "北京大学");
s2.introduce(); // 张三的介绍
// 使用部分参数构造函数
Student s3 = new Student("李四", 20);
s3.introduce(); // 李四的介绍,学校为"未知学校"
}
}5. this关键字
this 关键字指向当前对象:
5.1 区分成员变量和局部变量
public class Person {
String name;
int age;
public Person(String name, int age) {
// this.name 是成员变量
// name 是局部变量(参数)
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name; // 区分成员变量和参数
}
public String getName() {
return this.name;
}
}6. 封装
封装是面向对象的核心特性之一,隐藏内部实现,只暴露必要的接口。
6.1 访问修饰符
| 修饰符 | 同类 | 同包 | 子类 | 其他 |
|---|---|---|---|---|
public | ✓ | ✓ | ✓ | ✓ |
protected | ✓ | ✓ | ✓ | ✗ |
| 默认(包访问) | ✓ | ✓ | ✗ | ✗ |
private | ✓ | ✗ | ✗ | ✗ |
6.2 使用private封装属性
public class BankAccount {
private String accountNumber;
private double balance;
private String owner;
public BankAccount(String accountNumber, String owner, double initialBalance) {
this.accountNumber = accountNumber;
this.owner = owner;
this.balance = initialBalance;
}
// getter方法
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
// setter方法(带验证)
public boolean deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("存款成功,余额:" + balance);
return true;
} else {
System.out.println("存款金额必须大于0");
return false;
}
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("取款成功,余额:" + balance);
return true;
} else {
System.out.println("取款金额无效或余额不足");
return false;
}
}
}7. static关键字
static 表示"属于类"而非"属于对象"。
7.1 静态变量
所有对象共享同一个静态变量:
public class Student {
String name;
static String school; // 静态变量,所有学生共享
public Student(String name) {
this.name = name;
}
}
public class StaticDemo {
public static void main(String[] args) {
Student.school = "北京大学"; // 通过类名访问
Student s1 = new Student("张三");
Student s2 = new Student("李四");
System.out.println(s1.name + "的学校:" + s1.school); // 北京大学
System.out.println(s2.name + "的学校:" + s2.school); // 北京大学
// 修改静态变量,所有对象都受影响
Student.school = "清华大学";
System.out.println(s1.name + "的学校:" + s1.school); // 清华大学
}
}7.2 静态方法
不能访问非静态成员,只能访问静态成员:
public class MathUtils {
// 静态变量
static final double PI = 3.14159265;
// 静态方法
public static int add(int a, int b) {
return a + b;
}
public static double circleArea(double radius) {
return PI * radius * radius;
}
}
public class StaticMethodDemo {
public static void main(String[] args) {
// 通过类名调用静态方法
int sum = MathUtils.add(10, 20);
System.out.println("10 + 20 = " + sum);
double area = MathUtils.circleArea(5);
System.out.println("圆的面积:" + area);
}
}8. 实战案例
8.1 设计一个学生管理系统
public class StudentManager {
private String[] names;
private int[] scores;
private int count;
private int capacity;
public StudentManager(int capacity) {
this.capacity = capacity;
names = new String[capacity];
scores = new int[capacity];
count = 0;
}
public boolean addStudent(String name, int score) {
if (count >= capacity) {
System.out.println("学生数量已满");
return false;
}
if (score < 0 || score > 100) {
System.out.println("成绩无效");
return false;
}
names[count] = name;
scores[count] = score;
count++;
return true;
}
public void printAll() {
System.out.println("=== 学生列表 ===");
for (int i = 0; i < count; i++) {
System.out.println(names[i] + ":" + scores[i] + "分");
}
}
public double getAverage() {
if (count == 0) return 0;
int sum = 0;
for (int i = 0; i < count; i++) {
sum += scores[i];
}
return (double) sum / count;
}
}9. 总结
本篇我们学习了:
✅ 面向对象思想:类与对象的概念
✅ 类的定义:属性、方法、构造函数
✅ 对象的创建:new关键字、内存存储
✅ 构造函数:初始化对象、重载
✅ this关键字:指向当前对象
✅ 封装:访问修饰符、getter/setter
✅ static关键字:静态变量、方法、代码块
核心要点:
- 类是模板,对象是实例
- 构造函数用于初始化对象
- 封装保护数据安全
- static属于类而非对象
下一篇预告: 《Java从零到熟练(五):面向对象进阶》
- 学习继承和多态
- 理解接口和抽象类
- 掌握面向对象的高级特性
参考资源
到此这篇关于Java面向对象基础实例详解的文章就介绍到这了,更多相关Java面向对象基础内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
使用Spring Framework 时常犯的十大错误(小结)
这篇文章主要介绍了使用Spring Framework 时常犯的十大错误(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-07-07
Java Controller实现参数验证与统一异常处理流程详细讲解
Controller是Spring接受并处理网页请求的组件,是整个应用的入口,因此学会Controller的常用注解对理解一个应用是重中之重。SpringBoot的Controller中经常会用到注解@Controller、@RestController、@RequestMapping、@RequestBody等2023-01-01


最新评论