Inheritance/Multiple: Difference between revisions

From Rosetta Code
Content added Content deleted
(New task, C++ code)
 
(Added Java)
Line 25: Line 25:
};
};
</cpp>
</cpp>

=={{header|Java}}==
Java does not allow multiple inheritance, but you can "implement" multiple interfaces. Interfaces in Java aren't allowed to have any methods defined at all. When you implement an interface you must then define them (even if that definition is nothing a.k.a. empty curly braces).
<java>public interface Camera{
//functions here with no definition...
//ex:
//public void takePicture();
}</java>
<java>public interface MobilePhone{
//functions here with no definition...
//ex:
//public void makeCall();
}</java>
<java>public class CameraPhone implements Camera, MobilePhone{
//functions here...
}</java>

Revision as of 17:47, 27 April 2008

Task
Inheritance/Multiple
You are encouraged to solve this task according to the task description, using any language you may know.

Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes, others restrict it to interfaces, some don't allow it at all.

Write two classes (or interfaces) Camera and MobilePhone, then write a class CameraPhone which is both a Camera and a MobilePhone.

There is no need to implement any functions for those classes.

C++

<cpp> class Camera {

 // ...

};

class MobilePhone {

 // ...

};

class CameraPhone:

 public Camera,
 public MobilePhone

{

 // ...

}; </cpp>

Java

Java does not allow multiple inheritance, but you can "implement" multiple interfaces. Interfaces in Java aren't allowed to have any methods defined at all. When you implement an interface you must then define them (even if that definition is nothing a.k.a. empty curly braces). <java>public interface Camera{

  //functions here with no definition...
  //ex:
  //public void takePicture();

}</java> <java>public interface MobilePhone{

  //functions here with no definition...
  //ex:
  //public void makeCall();

}</java> <java>public class CameraPhone implements Camera, MobilePhone{

  //functions here...

}</java>