Java – interfaces and concrete classes

Below I have a person interface, an implementation class and a driver class, which initializes person with a name and outputs it again What are the advantages of using?

Person person = new PersonImpl();

replace

PersonImpl person = new PersonImpl();

Should the interface hide the implementation? Is this the right way to use the interface?

public class Driver {

    public static void main(String [] args)
    {
        Person person = new PersonImpl();
        person.setName("test name");
        System.out.println("Name is "+person.getName());
    }

}


public interface Person {

    public void setName(String name);

    public String getName();

}


public class PersonImpl implements Person{

    private String name;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Solution

This is how the interface is used

The reason is that you can write another implementation later without changing the code that uses person

So now you can use personimpl, but later you may need an othertypeofpersonimpl

You can create a new class that implements the same interface, and you can use the new class with any other code that expects a person

A good example is the list interface

List has multiple implementations, such as ArrayList, LinkedList, etc These have advantages and disadvantages By writing code that uses lists, you can let each developer decide which type of list works best for them and be able to handle any one without making any changes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>