Isn’t instantiating an object of type Interface illegal?

This answer describing how Spring for Java works instantiates an object of type Interface which is illegal yet it received 21 upvotes. Why is this answer upvoted for illegal behavior?

Spring contains (as Skaffman rightly pointed out) a MVC framework. To explain in short here are my inputs. Spring supports segregation of service layer, web layer and business layer, but what it really does best is “injection” of objects. So to explain that with an example consider the example below:

public interface FourWheel
{
   public void drive();
}

public class RoadTrip
{
    private FourWheel myCarForTrip;
}

6

What the user performed was a declaration of the interface, but not an instantiation. An instantiation would be as follows:

Fourwheel myFour = new FourWheel();

Declarations of interface types are legal because class types that implement that interface can be assigned to these declarations, shown below:

FourWheel newFour = new Sedan();

Alternatively, an anonymous inner class may be used:

Fourwheel myFour = new FourWheel() { public void say(){ System.out.println("Anonymous inner class");}};

17

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *