Junior — Middle
Is it possible to create a proxy for class A using class B?
sobes.tech AI
Answer from AI
Yes, it is possible to create a proxy for class A using class B. In this case, class B acts as an intermediary that holds a reference to an object of class A and overrides the necessary methods, adding additional logic (such as logging, caching, access control) before or after calling the methods of class A.
Example in Java:
class A {
void doSomething() {
System.out.println("Executing A");
}
}
class B {
private A a;
public B(A a) {
this.a = a;
}
void doSomething() {
System.out.println("Proxy B: before calling A");
a.doSomething();
System.out.println("Proxy B: after calling A");
}
}
// Usage:
A a = new A();
B proxy = new B(a);
proxy.doSomething();
Thus, class B serves as a proxy for class A, extending or controlling its behavior.