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
相关推荐
用户83562907805114 小时前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent18 小时前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
SamDeepThinking20 小时前
裁掉那个差程序员后,给你看团队里高手的代码:这个习惯,希望你有
java·后端·程序员
朕瞧着你甚好21 小时前
技术雷达 & Java 集成评估报告 — Apache Tika 3.3.1
java·ai编程
咕白m62521 小时前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
MacroZheng1 天前
短短几天,暴涨2.8万Star!又一款编程神器开源!
java·人工智能·后端
SamDeepThinking1 天前
函数式编程:用BiFunction消除多类型分支的代码重复
java·后端·面试
SelectDB2 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
Flittly2 天前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了2 天前
Java 生成二维码解决方案
java·后端