السلام عليكم
كلنا يعرف أن ال inheritance يستخدم لعمل extention لل superclass ف ال subclass ، و لكن هذا يكون ف ال compile-time أي قبل تنفيذ ال كود نعلم أن x يرث من y ، هناك طريقه أخري نستطيع بها في ال runtime تحديد من يرث من مَن ، و بهذا تزيد درجة المرونه في البرنامج ، و هي بإستخدام ال composition ، راجع هذا الكود البسيط و أنت تفهم
public void doSomeThing();
}
class C1 implements SuperClass{
private SuperClass sc;
public C1 ( SuperClass sc ){
this.sc = sc;
}
public void doSomeThing (){
sc.doSomeThing();
System.out.println (" inherited by C1 at runtime" );
System.out.println ( "And new funcationality added as well ");
}
}
class C2 implements SuperClass{
public void doSomeThing (){
System.out.print ("Funcationality on C2");
}
}
class C3 implements SuperClass {
public void doSomeThing(){
System.out.print ("Functionality on C3");
}
}
class Test{
public static void main (String[] args){
C2 c2 = new C2();
C3 c3 = new C3();
C1 c1 = new C1 ( c2 );
c1.doSomeThing();
C1 c11 = new C1 ( c3);
c11.doSomeThing();
}
}
interface SuperClass {و تيجة التشغيل هي :
Funcationality on C2 inherited by C1 at runtime
And new funcationality added as well
Functionality on C3 inherited by C1 at runtime
And new funcationality added as well
daz@compu10:~/java_work/interview$ java Test
اللهم إجعل عملي صالحا ، و إجعله لوجهك خالصا و لا تجعل لأحد غيرك فيه شيئا
آمين
