public interface Foo {
public void a();
public void b();
}
// used as the inner class
public class ConcreteFoo implements Foo {
public void a() {
// implementation for a
}
public void b() {
// implementation for b
}
}
public class MyContainerA implements Foo {
private Foo innerFoo;
public MyContainerA(Foo innerFoo) {
this.innerFoo = innerFoo;
}
public void a() {
// delegate the method call to the contained object
innerFoo.a();
}
public void b() {
// delegate
innerFoo.b();
}
public void methodOnlyInContainerA() {
}
}
public class MyContainerB implements Foo {
private Foo innerFoo;
public MyContainerB(Foo innerFoo) {
this.innerFoo = innerFoo;
}
public void a() {
innerFoo.a();
}
public void b() {
innerFoo.b();
}
public void methodOnlyInContainerB() {
}
}
其他地方:
Foo foo = new ConcreteFoo();
// both guys below use the same inner class
MyContainerA contA = new MyContainerA(foo);
MyContainerB contB = new MyContainerB(foo);
abstract class Shape
{
String color;
// these are abstract methods
abstract double area();
public abstract String toString();
// abstract class can have constructor
public Shape(String color) {
System.out.println("Shape constructor called");
this.color = color;
}
// this is a concrete method
public String getColor() {
return color;
}
}
class Circle extends Shape
{
double radius;
public Circle(String color,double radius) {
// calling Shape constructor
super(color);
System.out.println("Circle constructor called");
this.radius = radius;
}
@Override
double area() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public String toString() {
return "Circle color is " + super.color +
"and area is : " + area();
}
}
class Rectangle extends Shape{
double length;
double width;
public Rectangle(String color,double length,double width) {
// calling Shape constructor
super(color);
System.out.println("Rectangle constructor called");
this.length = length;
this.width = width;
}
@Override
double area() {
return length*width;
}
@Override
public String toString() {
return "Rectangle color is " + super.color +
"and area is : " + area();
}
}
public class Test
{
public static void main(String[] args)
{
Shape s1 = new Circle("Red", 2.2);
Shape s2 = new Rectangle("Yellow", 2, 4);
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}
输出:
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0
4条答案
按热度按时间7jmck4yq1#
扩展一下我的评论:你想要使用组合以及带有委托的decorator模式
例如:
其他地方:
kg7wmglp2#
当您需要引用公共祖先时,应该使用继承,而不是“共享”公共代码。你说这两个对象没有这种关系,但有共同的代码-显而易见的方法是将其分解到它自己的类(或接口或任何东西)中,并组合到你的对象中:
你没有举一个例子,所以我来补一个:
不需要继承及其固有的硬耦合(双关语)。
4ktjp1zp3#
对
Abstract
如果您有一些方法的默认实现,则类是正确的方法,否则您可以interface
.在抽象类方法中编写所有通用的逻辑片段,并使这些方法
abstract
如果希望子类重写实现,则不需要使它们成为抽象方法yxyvkwin4#
您可以创建一个抽象类,其中包含的方法在子类中具有相同的实现—您不必像这样重复自己:
实现可以如下所示:
输出:
抽象的优点
它减少了观察事物的复杂性。避免代码重复并提高可重用性。有助于提高应用程序或程序的安全性,因为只向用户提供重要的细节。
我希望这对你有帮助