CodeGym /Courses /Java Core /An interface is more than an interface. It's a behavior.

An interface is more than an interface. It's a behavior.

Java Core
Level 2 , Lesson 8
Available

"Hello, Amigo! It's me—again. I want to give you another point of view on interfaces. You see, most of the time a class is a model of a particular object. By contrast, interfaces are more like an object's abilities or roles, rather than the object itself."

For example, things such as cars, bicycles, motorcycles, and wheels are best represented as classes and objects. But their abilities, like «I can move», «I can carry people», and «I can park», are better represented as interfaces. Check out this example:

Java code Description
interface Moveable
{
void move(String newAddress);
}
Corresponds to the ability to move.
interface Driveable
{
void drive(Driver driver);
}
Corresponds to the ability to move.
interface Transport
{
void addStuff(Object stuff);
Object removeStuff();
}
Corresponds to the ability to carry cargo.
class Wheel implements Moveable
{
...
}
A «wheel» class. Has the ability to move.
class Car implements Moveable, Drivable, Transport
{
...
}
A «car» class. Has the ability to move, be driven by a person, and carry cargo.
class Skateboard implements Moveable, Driveable
{
...
}
A «skateboard» class. Has the ability to move and be controlled by a person.
3
Task
Java Core, level 2, lesson 8
Locked
Code entry
Sometimes you don't need to think, you just need to hammer it out! As paradoxical as it may seem, sometimes your fingers will "remember" better than your conscious mind. That's why while training at the secret CodeGym center you will sometimes encounter tasks that require you to enter code. By entering code, you get used to the syntax and assimilate some material. What's more, you combat laziness.

Interfaces greatly simplify the life of the programmer. Programs very often have thousands of objects, hundreds of classes, and just a couple dozen interfaces (roles). There are few roles, but they can be combined in many ways (classes).

The whole point is that you don't have to write code defining interaction with every other class. All you have to do is interact with roles (interfaces).

Imagine that you're a robotic builder. You have dozens of subordinate robots and each of them can have multiple skills. Suppose you need to urgently finish building a wall. You just take all the robots that have the ability to "build" and tell them to build the wall. You don't really care which robots do it. Let it be a robotic watering can. If it knows how to build, let it build.

Here's how it would look in code:

Java code Description
static interface WallBuilder
{
void buildWall();
}
Ability to «build a wall». Understands the command «build a wall» (has the appropriate method).
static class WorkerRobot implements WallBuilder
{
void buildWall()
 {
…
 }
}
static class GuardRobot implements WallBuilder
{
void buildWall()
 {
…
 }
}
static class WateringCan
{
…
}
Robots that have this ability/skill.

A watering can can't build a wall (it doesn't implement the WallBuilder interface).

public static void main(String[] args)
{
 //add all robots to a list
 ArrayList robots = new ArrayList();
 robots.add(new WorkerRobot());
 robots.add(new GuardRobot());
 robots.add(new WateringCan());

 //build a wall if you can
 for (Object robot: robots)
 {
  if (robot instanceof WallBuilder)
  {
   WallBuilder builder = (WallBuilder) robot;
   builder.buildWall();
   }
  }
 }
}
How do we give the command to build a wall?

"That's amazingly interesting. I never dreamed that interfaces could be such an interesting topic."

"And then some! Together with polymorphism, it's totally mind-blowing."

Comments (27)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
LuisRC Level 39, Gijón, Spain
7 February 2022
Today I've been reading this lesson and doing the tasks and currently I have a mess with all these new concepts, interface, abstraction .... I hope that as I go deeper into Java I would understand much better all of them.
Gellert Varga Level 23, Szekesfehervar, Hungary
10 January 2021
- All methods in an interface are public by default even if it's not declared as public in the written code. - When you override (implement) a method, the visibility can be only increased. You must not decrease visibility. So WorkerRobot and GuardRobot inherit a public buildWall() method, therefore the implemented buildWall() method must be declared as public in the Robot classes. But in the example written in the lesson, they didn't write any modifier before the method-implementation. So, this way the method would become "package-private", but this would be a decreasing of the visibility (compared to public), and this is not allowed. The compiler said: "error: buildWall() in GuardRobot cannot implement buildWall() in WallBuilder" and: "attempting to assign weaker access privileges; was public"
Chang You Level 47, Santa Rosa, United States
24 December 2020
"Together with polymorphism, it's totally mind-blowing."
Yug Level 16, Dehra Dun, India
21 August 2020
We cannot create object for interface. Then how is the object class object (robot) type casted to interface(wallBuilder) class object?

WallBuilder builder = (WallBuilder) robot;
Karas Level 20, Tampa, United States
17 November 2020
robot in this case is the parameter used in the for loop, each robot is actually the GuardRobot, WorkerRobot and the WatteringCan that is stored in the robots array, line 10, The code above then casts all of them to be WallBuilders, line 14, if they have the interface to buildWall(). In the case of the WatteringCan it will not as it is not an isnstanceof WallBuilder.
Chang You Level 47, Santa Rosa, United States
24 December 2020
There's no "New" in this line, so I think it's just "casting" not "creating".
Ashish RajAnand Level 13, Bhilai , India
14 May 2020
we create object of WorkerRobot ,GuardRobot , then how condition in if statement is true ?

if (robot instanceof WallBuilder)
Blaise Level 20, London, United Kingdom
19 May 2020
robot is either a WorkerRobot, a GuardRobot or a WateringCan. WallBuilder is an interface, so it is a sort of "class". WorkerRobot and GuardRobot both implements WallBuilder, so we can say WallBuilder is their parent class -> WorkerRobot is-a WallBuilder, GuardRobot is-a WallBuilder, just llike King is-a ChessFigure, Queen is-a ChessFigure. Now it should make sense why "if (robot instanceof WallBuilder)" is true. It's just a different way of saying "if (robot implements WallBuilder)" or "if (robot is-a WallBuilder).
Ashish RajAnand Level 13, Bhilai , India
20 May 2020
refer this I got concept.
Renat Mukhametshin Level 16, Pervouralsk, Russain Federation
30 August 2019
hmm, it's not ease as seems for the first glance
Jonaskinny Level 25, Redondo Beach, United States
25 February 2022
Its like saying... interface Moveable with one method move() interface Flies with one method fly() Man class implements Moveable, Flies Man's move() makes the man Walk Upright Man's fly() makes the man board an airplain Duck class implements Moveable, Flies Duck's move() makes the duck waddle Duck's fly() makes the duck flap its wings. Make one object of each, put them in a list of Moveables (and another of Flies), loop them and call .move() and then .fly()
Philip T-D Level 18, San Diego, United States
24 April 2019
In the last code example below the comment //build a wall if you can: Why can you not simply call robot.buildWall() on each object directly in the loop? Won't line 12 guarantee that the robot in question has the .buildWall() method? What's with the type coercion going on there (lines 14-15) ?
Roy Level 22, Bangkok, Thailand
25 April 2019
Good question.

 for (Object robot: robots)
 {
  if (robot instanceof WallBuilder)  //this already should avoid the robots that can't build the wall
  {
   robot.buildWall();          // instead of: WallBuilder builder = (WallBuilder) robot;
                                        //builder.buildWall();
   }
  }
Would be nice if someone could explain why it can't be like that
Ops guy Level 17, Round Rock, TX, United States
7 May 2019
If I understand this correctly robot's reference variable is type Object and Object doesn't know about buildWall method. So you need to cast Object type to WallBuilder type first in order to use that method. Object type and reference type is not the same. I hope I got this right :)
Julien Level 15, Paris, France
22 May 2019
that's what I would have answered. There is one line solution:

if (robot instanceof WallBuilder) {
    ((WallBuilder) robot).buildWall();
}
Ed Maphis Level 20, Painesville, United States
31 May 2019
The problem is that 'WateringCan' doen't implement 'WallBuilder'.
Muhammad Vahhaaj Level 19, Rawalpindi, Pakistan
5 July 2019
One thing that is clear is that, it is a widening reference conversion. So the reference type(Object class) used in foreach loop does not have the method buildWall() defined so it won't be able to run that method. Now what we are doing is that, casting the the object to its child class which hs the method defined and storing it in that reference type variable to explicitly tell that which method to run.
Syed Tayyab ul Mazhar Level 12, Karachi, China
17 May 2020
In line 10:

for (Object robot: robots)
robot is of type Object and, Object class doesn't have buildWall method. So, we've to cast robot to a WallBuilder, so that we can call buildWall method. The following line checks if the object referenced by robot is a WallBuilder before casting it.

if (robot instanceof WallBuilder)
Onur Bal Level 27, Istanbul, Turkey
14 September 2020
So we cannot create a WallBuilder object, because it is an Interface. But why can we cast an object to the type of WallBuilder, then?
Chang You Level 47, Santa Rosa, United States
24 December 2020
That's exactly the point
Chang You Level 47, Santa Rosa, United States
24 December 2020
"Casting"(already exist but to change type) is different from "creating"(didn't exist), The "creating" process for Robots is basically "implementation", since they're already "created" (as Objects) when they're implemented thus already exist, we only need to cast them to WallBuilder interface so as to call the buildWall method.
Darko Jakimovski Level 18, Kriva Palanka, Macedonia, The Former Yugoslav Republic of
24 April 2019
Can anyone explain why would an interface be static? Couldn't find anything on the subject
Oleg Tokarenko Level 19, L'viv, Ukraine
15 May 2019
I assume, that's because an interface is a general behaviour that classes implement. Therefore, if the field is static it means that all instantiated objects can use the same general field. You can apply this analogy to interfaces: all of the classes can implement the same general interface. That's how I understand it.
Darko Jakimovski Level 18, Kriva Palanka, Macedonia, The Former Yugoslav Republic of
15 May 2019
I still haven't wrapped my head around the concept, but I'm sure I'll have the Eureka moment as with everything Java related. Thanks for the effort tho Oleg, cheers
Iasu Level 18, Norway
1 June 2019
Same here! I got "modifier static is redundant for inner interface" in IntelliJ
Vidhya Level 16, Sunnyvale, United States
17 December 2019
when a Interface has a inner interface embedded (Nested interfaces)ideally they define it as static (same is the case with class identifier).please find a detailed explanation https://stackoverflow.com/questions/8374646/what-is-a-static-interface-in-java
Chang You Level 47, Santa Rosa, United States
24 December 2020
As the title points out, an interface is, in essence, the common behaviors shared by classes(that implemented it)