3

I am looking at the Interface chapter provided on the Java website
Using Interface as a type
So my understanding was that the whole point of interface is that it is like a class but it's not possible to form objects from it, but this page says how to use interface as a data type. the line Relatable obj1 = (Relatable)object1; seems to create an object of type Relatable which is an interface. Although I must say that the new keyword has not been used here, thus not really creating a reference to an object of type Relatable. Is that really the cause for this line NOT creating an object of type Relatable?

Again, it further says

If you make a point of implementing Relatable in a wide variety of classes, the objects instantiated from any of those classes can be compared with the findLargest() method—provided that both objects are of the same class.

What does this mean? Does this mean anything that implements Relatable can call findLargest()? If it's so, why does it say provided that both objects are of the same class?

----- EDIT -----
From the previous chapters of this tutorial:
Definition of relatable:

public interface Relatable {

    // this (object calling isLargerThan)
    // and other must be instances of 
    // the same class returns 1, 0, -1 
    // if this is greater // than, equal 
    // to, or less than other
    public int isLargerThan(Relatable other);
}  

Using relatable as a type:

public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ((obj1).isLargerThan(obj2) > 0)
      return object1;
   else 
      return object2;
}

----- EDIT 2 -----
In the chapter on anonymous classes, it does this:

public class HelloWorldAnonymousClasses {

    interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);
    }
.
.
.
 HelloWorld englishGreeting = new EnglishGreeting();

        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };

So how does this work?

1
  • "implements Relatable can call findLargest()" - that depends on findLargest(). Do you have the signature for that? My guess is that it will accept Relatables. Commented Jul 22, 2013 at 9:24

5 Answers 5

4

the line Relatable obj1 = (Relatable)object1; seems to create an object of type Relatable

No. This line creates a reference (obj1) of type Relatable and assigns it to object1. In order for this to work, object1 has to be cast to the (interface) type Relatable.
No new objects are being created here.

Does this mean anything that implements Relatable can call findLargest()?

Yes.

If it's so, why does it say provided that both objects are of the same class?

It has to do with the implementation of isLargerThan(). Since any class implementing the Relatable interface can't know anything about other classes implementing it, they can't do meaningful comparisons with other classes. Therefore, in order for this to work, both objects need to be of the same class.

Response to EDIT 2

So how does this work?

Instead of first defining a class and then creating an instance of it, as in the case with the EnglishGreeting, the frenchGreeting is created on the fly. What happens under the cover is that a new class implementing HelloWorld is created, just like in the english case, only this time it is anonymous (you never get to give it a name). It is just a convenience shortcut for those times when you need a one-time implementation of an interface.

Sign up to request clarification or add additional context in comments.

4 Comments

Does object1 have to be an object of a class that implements Relatable?
Thank you for your answer. I still don't quite understand about anonymous class in edit 2. Isn't it creating a nameless instance of the HelloWorld interface? Or is it a completely new nameless class which just happens to overload the methods of HelloWorld?
It's the second alternative, a totally new class that implements the HelloWorld interface.
so is it working as if I had declared class MyHelloWorld implements HelloWorld{ ... }, then done MyHelloWorld frenchGreeting = new MyHelloWorld();? Does this mean any anonymous class can be written using this alternative notation?
3

Interface types belong to the category of reference types in java. You can never instantiate an interface, but it can be assigned references to any of the objects of classes which implement it:

A variable whose declared type is an interface type may have as its value a reference to any instance of a class which implements the specified interface.

Interfaces are like behaviors. If a class happens to implement an interface, lets say Serializable, this adds a behavior to the class, which is, the class can be serialized.

This helps you introduce abstraction in your code. For example lets assume that you need a method in one of your utility classes which will be responsible for the actual job of serialization. Without interfaces you will end up writing a lot of methods, one for each object type that you want to serialize. Now imagine if you asked each of those objects to take care of their serialization themselves (by implementing a serialize method declared in the interface they implemented). With such implementation you need to write only one utility method for serialization. This method can take an argument of Serializable type, and instances of any class implementing this interface can be passed to the method. Now within the method you only need to invoke the serialize method on the interface variable. At runtime this will result in actual object's serialize method getting invoked.

Hope I was able to keep it simple.

Comments

2

Interface in Java is a mutual structure for classes that implement the interface, so the classes benefit from the methods/other member of that interface in their own way, which is called polymophism,

interface A
{
  // method header only declared here, so implementation can vary between classes
  public int foo(); 
}

class B implements A
{
   public override String foo()
   {
     return "Class B";
   }
}

class C implements A
{
   public override String foo()
   {
     return "Class C";
   }
}

so you can call foo() both from class B and C but they will react differently since they implement that method in their own way

1 Comment

Very clear, but I feel that there's more--much more.
2

An interface is just a class that defines the behaviour of an object, but not the underlaying implementation of it. By making Relatable obj1 = (Relatable)object1; you are just casting the object1 to a Relatable type, and therefore you can call any of the methods defined in the Relatable interface

Comments

1

To your first question about Relatable obj1 = (Relatable)object1;:

A simple Relatable obj1; will not create an instance of Relatable, but specifies that any object assigned to it must be of a type implementing the Relatable-interface.

Therefore any object that is to be cast, must be of a type implementing the Relatable-interface.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.