JAVA 面向对象 oop 简单了解
JAVA 面向对象oop
面向对象编程 (OOP) 是 Java 的基石。它通过类和对象来组织代码,旨在使程序设计更贴近现实世界,提高代码的可读性、可维护性和复用性。
一 ,基础介绍
1.类的组成要素
属性:描述对象特征的变量,例如一个Person类可能有name、age等属性。
方法:定义对象行为的函数,例如Person类可以包含walk()、speak()等方法。
class 类名{
int a; //属性
String b = "aaa";//这也是属性
}
2.类的实例化( 即对象)
对象里面包含属性和方法
通过类创建具体对象的过程称为实例化。例如:
person1 person1 = new person1();//创捷类的实例
person1.speak() # 调用方法 可以调用一个类的多个属性
person1.eat()
// new person1.speak() # 调用方法 只可以调用一个属性
person1 = Person("Alice", 25) # 创建Person类的实例
public void eat(){
int a; //属性
} //方法
int b; //属性
状态的实现示例
public class Player {
private int health; // 状态变量:生命值
private String name; // 状态变量:名称
public Player(String name, int health) {
this.name = name;
this.health = health;
}//构造函数
public void takeDamage(int damage) {
health -= damage; // 修改状态
}
public int getHealth() {
return health; // 获取状态
}
}
二 ,封装
-
将类的属性(变量)设置为
private(私有),外部无法直接访问。 -
提供公有
public的 Getter (获取/读取) 和 Setter (设置/修改) 方法,作为与外部交流的唯一窗口。 -
封装(Encapsulation):隐藏内部实现,通过公共方法访问数据。
1.定义私有属性
将类的属性声明为私有(private),禁止外部直接访问。例如:
public class Example {
private String name;
private int age;
}
提供公共方法(Getter/Setter)
通过公共方法(如getName()、setAge())控制对属性的访问和修改,可在方法中添加逻辑校验:
2.public
public class Example {
private String password; // 私有属性,外部无法直接访问
}
3.public
public class Example {
public String name; // 对外公开的属性
}
|
修饰符 |
类内 |
同包 |
子类 |
其他包 |
|---|---|---|---|---|
|
private |
✔ |
✖ |
✖ |
✖ |
|
protected |
✔ |
✔ |
✔ |
✖ |
|
public |
✔ |
✔ |
✔ |
✔ |
三,继承
1.继承:
子类继承父类的属性和方法,实现代码复用。
继承是实现代码复用的主要手段。它允许子类自动拥有父类(基类)的非私有属性和方法。它建立了类之间的层次结构。
class Parent:
def method(self):
print("Parent method")
class Child(Parent):
pass
2.继承的用途
-
代码复用:避免重复编写相同逻辑。
-
方法重写(Override):子类可重新定义父类方法以实现特定行为。class Parent: def method(self): print("Parent's method") class Child(Parent): def method(self): print("Child's modified method")
class Parent:
def method(self):
print("Parent's method")
class Child(Parent):
def method(self):
print("Child's modified method")
方法重写与super()调用
-
多态(Polymorphism):同一方法在不同类中有不同实现(如方法重写、接口实现)。
多态性是 OOP 最灵活的特性,它允许我们以统一的方式(使用父类的引用)来处理不同子类的对象
编译时多态(静态多态)
通过方法重载(Overloading)实现,在编译时根据参数类型和数量确定调用的方法。
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
四 ,运行时多态(动态多态)
1.多态的实现条件
-
继承关系:子类继承父类。
-
方法重写:子类重写父类的方法。
-
向上转型:父类引用指向子类对象(如
Animal a = new Dog())。
2.通过方法重写(Overriding)实现,
在运行时根据对象的实际类型调用方法。需满足继承关系和方法重写条件。
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Bark"); }
}
。
更多推荐



所有评论(0)