Python转Java系列:面向对象基础

第 4 章:面向对象基础

Python 对照表

Python Java
class Dog: class Dog { }
def __init__(self, name) 构造方法 Dog(String name)
self.name = name this.name = name
实例方法第一个参数 self 隐式 this
@classmethod / @staticmethod static 方法、静态工厂
多继承 class A(B, C) 单继承 extends,多接口 implements
super().__init__() super() 调用父类构造
鸭子类型 接口 interface 显式契约

4.1 定义类与对象

Python:

python 复制代码
class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def greet(self) -> str:
        return f"Hi, I'm {self.name}"

user = User("Alice", 30)
print(user.greet())

Java:

java 复制代码
public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String greet() {
        return "Hi, I'm " + name;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
}

// 使用
User user = new User("Alice", 30);
System.out.println(user.greet());

关键差异

  1. new 关键字 :Java 对象必须用 new 创建
  2. 字段默认包私有 :企业代码习惯 private + getter/setter
  3. 无动态添加属性:类定义时就要声明字段

4.2 封装

Python 用 _name / __name 约定;Java 用访问修饰符 + getter/setter。

Python(property):

python 复制代码
class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("radius must be >= 0")
        self._radius = value

Java:

java 复制代码
public class Circle {
    private double radius;

    public Circle(double radius) {
        setRadius(radius);
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        if (radius < 0) {
            throw new IllegalArgumentException("radius must be >= 0");
        }
        this.radius = radius;
    }

    public double area() {
        return Math.PI * radius * radius;
    }
}

💼 面试点 :为什么字段要 private?------ 封装、校验、便于重构。

4.3 继承

Python:

python 复制代码
class Animal:
    def speak(self):
        raise NotImplementedError

class Dog(Animal):
    def speak(self):
        return "Woof"

Java:

java 复制代码
public abstract class Animal {
    public abstract String speak();
}

public class Dog extends Animal {
    @Override
    public String speak() {
        return "Woof";
    }
}
Python Java
隐式继承 object 隐式继承 Object
重写方法 @Override 注解(推荐)
abc.ABC abstract class / interface
java 复制代码
Animal a = new Dog();
System.out.println(a.speak());  // 多态

4.4 接口

Java 单继承,但可实现多个接口------类似 Python 的 Protocol / 多 mixin 的常用替代。

Python(Protocol):

python 复制代码
from typing import Protocol

class Drawable(Protocol):
    def draw(self) -> None: ...

Java:

java 复制代码
public interface Drawable {
    void draw();
}

public class Button implements Drawable {
    @Override
    public void draw() {
        System.out.println("Drawing button");
    }
}

Java 8+ 接口可有 default 方法:

java 复制代码
public interface Logger {
    void log(String msg);

    default void logError(String msg) {
        log("[ERROR] " + msg);
    }
}

4.5 toString / equals / hashCode

Python Java
__str__ toString()
__eq__ equals(Object o)
__hash__ hashCode()
java 复制代码
@Override
public String toString() {
    return "User{name='" + name + "', age=" + age + "}";
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof User other)) return false;
    return age == other.age && Objects.equals(name, other.name);
}

@Override
public int hashCode() {
    return Objects.hash(name, age);
}

💼 面试点 :重写 equals 必须同时重写 hashCode(用于 HashMap 等)。

4.6 静态成员

Python:

python 复制代码
class Counter:
    count = 0

    @classmethod
    def increment(cls):
        cls.count += 1

Java:

java 复制代码
public class Counter {
    private static int count = 0;

    public static void increment() {
        count++;
    }

    public static int getCount() {
        return count;
    }
}

本章小结

  • Java OOP 更「显式」:访问修饰符、接口、单继承
  • private 字段 + 公开方法实现封装
  • abstract classinterface 分工:is-a 用继承,can-do 用接口
  • 记住 equals / hashCode / toString 三件套

练习题

  1. 实现 BankAccount:存款 deposit、取款 withdraw(余额不足抛异常)、查询 getBalance
  2. 定义接口 Payable,含 pay(double amount);让 BankAccount 实现它(可空实现或记录日志)。
  3. RectangleSquare(继承或组合,说明你的选择)。
  4. User 正确实现 equalshashCode
相关推荐
持敬chijing12 分钟前
PHP开发-环境搭建-安装phpstudy-vscode工具
开发语言·vscode·php
2401_8685347836 分钟前
MATLAB:车牌识别
python·django
卷无止境37 分钟前
用 FastAPI 撑起大文件的上传下载:从流式处理到断点续传的完整实践
后端·python·fastapi
xiaohaiAIgeo40 分钟前
【2026年】ASHRAE 110与EN 14175通风柜测试标准对比:进口与国产品牌性能差距
java·前端·数据库·科普知识
charlie11451419143 分钟前
Cinux · 第一次跳进 Ring 3:用户态与特权隔离
开发语言·c++·操作系统·开源项目
躺不平的理查德1 小时前
Windows C++ 第三方库使用流程备忘录--OpenCV
开发语言·c++
张龙6871 小时前
别再裸调大模型了:用 60 行 Python 给 LLM 调用加上「重试 + 超时 + 降级」
python
菜冻鱼1 小时前
Python-sklearn-评估指标
开发语言·人工智能·python·机器学习·numpy·pandas·sklearn
guyiICtestsocket1 小时前
国内支持定制的手机LPDDR芯片测试座工厂多种结构
人工智能·python·智能手机