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
相关推荐
咩咩啃树皮10 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
灯澜忆梦10 小时前
GO_并发编程---定时器
开发语言·后端·golang
鱟鲥鳚10 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
-银雾鸢尾-11 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-11 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白12 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
麻雀飞吧12 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
腾渊信息科技公司13 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地14 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
wuqingshun31415914 小时前
TCP超时重传机制是为了解决什么问题?
java