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 class 与 interface 分工:is-a 用继承,can-do 用接口
  • 记住 equals / hashCode / toString 三件套

练习题

  1. 实现 BankAccount:存款 deposit、取款 withdraw(余额不足抛异常)、查询 getBalance。
  2. 定义接口 Payable,含 pay(double amount);让 BankAccount 实现它(可空实现或记录日志)。
  3. 写 Rectangle 与 Square(继承或组合,说明你的选择)。
  4. 为 User 正确实现 equals 和 hashCode。
相关推荐
小白快快跑哦18 分钟前
python-字符串全解(六):正则表达式-量词
python·正则表达式·字符串
自强的小白19 分钟前
核心功能(Service接口)
java·mybatis
禹凕35 分钟前
机器学习之Selenium(Machina Learning about Selenium)
爬虫·python·selenium·测试工具·机器学习
乌暮1 小时前
深入理解 Java 泛型:把「万能盒子」用对、用稳
java·开发语言·后端·学习
大猫和小黄2 小时前
深入理解 Java Optional:从设计哲学到工程实战
java
数据库百宝箱2 小时前
rum&gin索引对比
java·数据库·gin
2601_962218612 小时前
C语言中三种库的编译和使用方法
开发语言·c++
传奇开心果编程2 小时前
中庸、有容、破执:仓颉编程语言的中华智慧结晶——三重哲学境界思辨
开发语言·华为·开源·软件工程
yychen_java2 小时前
第六篇:Spring AI 实战:将 Java 业务接口封装成企业级 MCP Server
java·人工智能·spring