-3

What is the type of a class if it implements more than one interface?

For example if the class Example implements Interface1 doesExample become of type Interface1? If so what happens if it also implements Interface2. What type is class Example then?

Neil Masson
  • 2,609
  • 1
  • 15
  • 23

2 Answers2

2

The phrase "become of type interface1" is not clear.

In OO design, a class is supposed to represent a particular "object" or "thing" in your problem domain. If you're writing a system to model vehicles on highways, you might have classes (or interfaces) for "vehicle", "road", etc.

Let's say a part of the system also dealt with commercial vehicles; taxes or something. So there might be a class of "vehicle" and an interface of "CommercialVehicle", with the latter providing methods to get attributes connected with road taxes for the vehicle. Not all Vehicles would be CommercialVehicles, but some of them would implement that interface.

An object of type Vehicle might or might not implement that interface. IF it does implement the interface, that guarantees that it has the associated methods. You can use the "instanceof" operator to determine whether a particular object implements an interface or not.

But I'm not sure what you mean by "become of type interface", so I'm not sure how to answer that question.

arcy
  • 12,845
  • 12
  • 58
  • 103
0

Implementing is for interfaces. Extending is for classes.
In Java, you can implement many interfaces, but extend only one.

If you extend a class, you don't become anything, but you do inherit its members (fields, methods, subclasses).

As per your (vague) question, let's assume:

public interface Interface1 {
    void myMethod(Interface1 other); // using public is redundant in interfaces
}

public class Example implements Interface1, Interface2 { ... }

Then Example is of type Example (...), and when I need to implement the methods in the interface then:

public void myMethod(Interface1 myObject) {
    Example myClass = (Example)myObject;
}

I need to cast to use the methods from Example.

Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75