可能是重复问题:
优先使用组合还是继承?
在Java中,继承和委托有什么区别?
如何在我的项目中使用以下示例?请您指导如何使用委托。我知道继承的概念,但对于委托并不了解。因此,请给出合适的理由。为什么应该使用这个方法?
package com.m;
class RealPrinter { // the "delegate"
void print() {
System.out.println("something");
}
}
class Printer { // the "delegator"
RealPrinter p = new RealPrinter(); // create the delegate
void print() {
p.print(); // delegation
}
}
public class Tester {
// to the outside world it looks like Printer actually prints.
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}