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
相关推荐
逻辑星辰1 小时前
x-ds-pow-response逆向分析
开发语言·人工智能·python·深度学习·算法
DIY源码阁1 小时前
JavaSwing酒店管理系统 - MySQL版
java·mysql·eclipse
c_lb72881 小时前
涨跌停与流动性变差还要不要挂单:quote 涨跌停字段与熔断思路
python·区块链
非生而知之者1 小时前
基于灰狼算法优化的电量预测
python·算法·群体智能算法·电力预测
不恋水的雨1 小时前
easyexcel快速填充大数据量不覆盖后面的行解决方式
java·excel·poi
AI科技星2 小时前
《全域数学/数术工坊》体系总览
c语言·开发语言·汇编·electron·概率论
范什么特西2 小时前
Maven中dependencies和dependencyManagement区别
java·开发语言·maven
SunnyDays10112 小时前
Java 操作 Word 超链接:添加网页、邮箱、文件和图片链接
java·word·超链接
techdashen2 小时前
Rust 项目进展月报:2026 年 1 月
开发语言·后端·rust