Java基础(复习一) —— 面向对象编程(OOP)
面向对象编程(OOP)的3大特性:封装、继承、多态。
封装(Encapsulation)
利用抽象数据类型将数据和基于数据的操作封装在一起,使其构成一个不可分割的独立实体。具体的做法是隐藏对象的实现细节,并提供接口来访问这些对象,用户无需知道class内部的实现只需要知道如何使用class提供的方法。
例子:
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
public double getBalance() {
return balance;
}
}
在这个例子中,银行账户类封装了账户余额的实现。它允许存款,取款和查询余额,但不允许直接修改余额。这样做可以保护账户余额的完整性,并避免错误地更改余额。
继承(Inheritance)
继承是允许创建一个类,该类使用extends关键继承另一个类的属性和行为。继承是一种"is-a" 关系,指一个类是另一个类的一种特殊情况。
class Human {
protected String name;
public Human(String name) {
this.name = name;
}
public void talk() {
System.out.println(name + " is talking.");
}
}
//Man is-a Human
class Man extends Human {
public Man(String name) {
super(name);
}
public void playSports() {
System.out.println(name + " is playing sports.");
}
}
public class TestRun {
public static void main(String[] args) {
Man man = new Man("John");
man.talk();
man.playSports();
}
}
//result:
John is talking.
John is playing sports.
private与protected的差异:
private修饰符 | 私有的,仅在当前类内可见,不能被子类继承。 |
protected修饰符 | 受保护的,当前类和其子类及相同package的类中可见,不能被其他类中访问。 |
向上转型
父类引用指向子类对象,称为向上转型。创建了一个 Student 对象,然后将其分配给类型为 Person 的引用。这是一个向上转型的示例,其中父类类型的引用指向子类类型的对象。
class Person {
public void walk() {
System.out.println("Person is walking");
}
}
class Student extends Person {
public void study() {
System.out.println("Student is studying");
}
}
public class UpcastingExample {
public static void main(String[] args) {
Person person = new Student(); // 向上转型
person.walk(); // 输出 "Person is walking"
// person.study(); // 编译错误,因为 walk() 只在 Person 类中定义
}
}
多态(Polymorphism)
多态是指由继承而产生的相关的不同的类,其对象对同一消息会做出不同的响应。这样,同一操作在不同的对象上可以有不同的实现,即父类引用指向子类对象,在调用方法时,将会执行子类重写的方法。
Java实现多态有三个必要条件:继承、重写、向上转型。
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Animal object
Animal myPig = new Pig(); // Pig extends Animal, 向上转型
Animal myDog = new Dog(); // Dog extends Animal, 向上转型
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
运行结果:
The animal makes a sound
The pig says: wee wee
The dog says: bow wow
本文只是个人(EnergyNo8)学习笔记如有错误请网友指出。
如有引用或转载请标明出处!
努力、坚持,总会有收获!
______ EnergyNo8