# OOAD Lab 4, 5 (03/16) ###### tags: `OOAD` --- [TOC] --- ## 4. Multiple Inheritance (in C++ and Java) - **Percolating upward** - e.g. 將有需要的 virtual function 向上移 - If we percolated up more methods as we built these classes, Car becomes bloated and confused. Generally, only functionality common to all subclasses belongs in a base class. - **Runtime Type Identification (RTTI)** - **This means that as a program is running it is possible to determine the exact type of object a pointer or reference refers to.** - **casting down** - We have casted a base class pointer down its hierarchy into a subclass pointer. - **C++: `Sub* sub_ptr = dynamic_cast<Sub*>(base_ptr);`** - **java: `if(obj instanceof Sub) ...`** - **Explicitly checking an objects type is usually indicative of bad design** - **spaghetti code** - **無法做到與未來擴充的型別無關** - **Vehicle <- Car, Vehicle <- Jet, JetCar <- (Jet, Car)** - **JetCar called Vehicle's constructor twice** - **Ambiguity can happen when you use multiple inheritance** 1. **Ambiguity can happen when you use multiple inheritance** - **C++: `sub_ptr->Base::foo()`** 2. **Override** - **解決重複基底類別繼承:** - **鑽石形繼承 diamond-shaped inheritance** - **C++:** ```cpp class Sub1 : virtual Base {}; class Sub2 : virtual Base {}; class SubSub : Sub1, Sub2 {}; ``` - **Java Interface** - **Java prohibits multiple inheritance** - **Only virtual function declarations** in interfaces - **Java:** ```java interface Foo { void bar(); } class Sub extends Base implements Foo {} ``` - **In principle, implementing an interface has loosen inheritance principle to follow because there is no attributes (variables) to inherit from implement** - **~~is-a~~ ---> can-do** ## 5. Comparison of C++ and Java | human | |:-------:| | human | | student | | human | | teacher | | 講師 |