在面向对象编程中,一个类中的方法需要访问另一个类的方法,通常有以下几种实现方式:
Car
类包含一个Engine
类实例。UserService
类依赖于UserRepository
,可以通过构造函数注入不同的UserRepository
实现。Shape
接口,不同的图形类(如Circle
、Square
)实现该接口。假设我们有两个类ClassA
和ClassB
,ClassA
需要访问ClassB
的方法。
class ClassB {
void methodB() {
System.out.println("Method B");
}
}
class ClassA {
private ClassB classB;
public ClassA(ClassB classB) {
this.classB = classB;
}
void eventHandler() {
// 访问ClassB的方法
classB.methodB();
}
}
public class Main {
public static void main(String[] args) {
ClassB b = new ClassB();
ClassA a = new ClassA(b);
a.eventHandler();
}
}
interface Service {
void execute();
}
class ServiceImpl implements Service {
@Override
public void execute() {
System.out.println("Service implementation");
}
}
class EventHandler {
private Service service;
public EventHandler(Service service) {
this.service = service;
}
void handleEvent() {
service.execute();
}
}
public class Main {
public static void main(String[] args) {
Service service = new ServiceImpl();
EventHandler handler = new EventHandler(service);
handler.handleEvent();
}
}
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a square");
}
}
class ShapeDrawer {
private Shape shape;
public ShapeDrawer(Shape shape) {
this.shape = shape;
}
void drawShape() {
shape.draw();
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle();
ShapeDrawer drawer = new ShapeDrawer(circle);
drawer.drawShape();
Shape square = new Square();
drawer = new ShapeDrawer(square);
drawer.drawShape();
}
}
问题:在eventHandler
方法中无法访问另一个类的方法。
原因:
解决方法:
public
的。public
的。通过以上方法,可以有效解决在类中访问另一个类方法时遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云