-1

I got one Interface and one Class.

public interface IUser{
    public String getFirstname();
    public String getLastname();
}

public class User implements Iuser{
    String firstname;
    String lastname;

    public User(String firstname, String lastname)
    {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public String getFirstname(){
        return firstname;
    }

    public String getLastname(){
        return lastname;
    }
}

When I usually need to create an instance of an User I would do:

User user = new User("Mike", "L");

But I am confused with articles that I found on the internet, because they are creating an instance of an User-object like this:

IUser user = new User("Mike", "L");

I would like to know why programmers are creating an User instance with the Interface in front of it?

What is the reason of creating an instance in this way?

Why would you prefer IUser user = new User() instead of User user = new User()?

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
Swag
  • 2,090
  • 9
  • 33
  • 63

4 Answers4

0

You could have different objects that implement the same interface.

It doesn't matter what the underlying implementation is, all that matters is that the object that implements the IUser interface has methods that allow it to getFirstName and getLastName.

It's an added layer of abstraction that makes your code simpler and more organized.

claudio
  • 1,465
  • 16
  • 26
0

The idea is that code following that call only know how to work with the Interface. They don't care how or what the object really is, so long as the Interface is maintained. One could make many implementations of the same interface and follow-on code would not care.

By only passing around the implementing class (User), all follow on code must be that type. The case for a single User does not really need an interface, especially if you can guarantee that scope. But, if you were to have User, SuperUser, RestrictedUser, etc. - how they implement different methods could be specific to them, while code that uses the interface will simply care they can "do what users can do" (e.g. "have implemented the interface")

clay
  • 5,917
  • 2
  • 23
  • 21
0

It's called polymorphic assignment, read this thread, it might give you some clues: http://www.dreamincode.net/forums/topic/132538-what-is-polymorphic-assignment/

Lucas
  • 3,181
  • 4
  • 26
  • 45
0

This is useful for polymorphism in Object Oriented programming language. For example you can have:

public class BadUser implements Iuser{
  ...
}

public class GoodUser implements Iuser{
  ...
}

and one method like this:

void authenticated(Iuser user);

would work with:

Iuser a = new BadUser();
Iuser b = new GoodUser();
authenticate(a); //OK;
authenticate(b); //OK;

but this wont work for:

void authenticated(GoodUser user);
Iuser a = new BadUser();
Iuser b = new GoodUser();
authenticate(a); //Error;
authenticate(b); //OK;
hawks
  • 114
  • 1
  • 4