Sunday, May 28, 2017

Introduction to Java programming, Part 2 (6)

Interfaces


In this section, you begin learning about interfaces and start using them in your Java code.

Interfaces: What are they good for?

As you most likely are aware from the past area, unique strategies, by configuration, determine an agreement—through the technique name, parameter(s), and return sort — yet give no reusable code. Dynamic strategies — characterized on unique classes — are helpful when the way the conduct is actualized is probably going to transform from the way it's executed in one subclass of the conceptual class to another. 

When you see an arrangement of basic practices in your application (think java.util.List) that can be gathered together and named, yet for which at least two executions exist, you should seriously mull over characterizing that conduct with an interface—and that is the reason the Java dialect gives this element. Be that as it may, this genuinely propelled highlight is effectively mishandled, muddled, and contorted into the most horrifying shapes (as I've seen direct), so utilize interfaces with alert. 

It may be useful to consider interfaces along these lines: They resemble unique classes that contain just theoretical techniques; they characterize just the agreement however none of the usage.

Defining an interface

The syntax for defining an interface is straightforward:
public interface InterfaceName {
    returnType methodName(argumentList);
  }
An interface assertion resembles a class affirmation, aside from that you utilize the interface catchphrase. You can name the interface anything you need to (subject to dialect rules), however by tradition, interface names look like class names. 
Strategies characterized in an interface have no technique body. The implementer of the interface is in charge of giving the technique body (as with theoretical strategies). 
You characterize chains of importance of interfaces, as you accomplish for classes, aside from that a solitary class can execute the same number of interfaces as you need it to. Keep in mind, a class can expand just a single class. On the off chance that one class amplifies another and executes an interface or interfaces, you list the interfaces after the developed class, this way:
public class Manager extends Employee implements BonusEligible, StockOptionRecipient {
  // And so on
}
An interface doesn't need to have any body at all. The following definition, for example, is perfectly acceptable:
public interface BonusEligible {
}
Generally speaking, such interfaces are called marker interfaces, because they mark a class as implementing that interface but offer no special explicit behavior.
Once you know all that, actually defining an interface is easy:
public interface StockOptionRecipient {
  void processStockOptions(int numberOfOptions, BigDecimal price);
}

Implementing interfaces

To define an interface on your class, you must implement the interface, which means that you provide a method body that provides the behavior to fulfill the interface's contract. You use the implements keyword to implement an interface:
public class ClassName extends SuperclassName implements InterfaceName {
  // Class Body
}
Suppose you implement the StockOptionRecipient interface on the Manager class, as shown in Listing 17:
Listing 17. Implementing an interface
public class Manager extends Employee implements StockOptionRecipient {
  public Manager() {
  }
  public void processStockOptions (int numberOfOptions, BigDecimal price) {
    log.info("I can't believe I got " + number + " options at $" +
    price.toPlainString() + "!");
  }
}
When you actualize the interface, you give conduct to the technique or strategies on the interface. You should execute the techniques with marks that match the ones on the interface, with the expansion of the free modifier. 
A dynamic class can proclaim that it actualizes a specific interface, yet you're not required to execute the majority of the strategies on that interface. Unique classes aren't required to give usage to the greater part of the techniques they claim to actualize. In any case, the main solid class (that is, the first that can be instantiated) must actualize all strategies that the progressive system doesn't execute. 
Note: Subclasses of a solid class that actualizes an interface don't have to give their own particular execution of that interface (in light of the fact that the strategies on the interface have been actualized by the superclass).

Generating interfaces in Eclipse

Eclipse can easily generate the correct method signature for you if you decide that one of your classes should implement an interface. Just change the class signature to implement the interface. Eclipse puts a red squiggly line under the class, flagging it to be in error because the class doesn't provide the methods on the interface. Click the class name, press Ctrl + 1, and Eclipse suggests "quick fixes" for you. Of these, choose Add Unimplemented Methods, and Eclipse generates the methods for you, placing them at the bottom of the source file.

Using interfaces

An interface defines a new reference data type, which you can use to refer to an interface anywhere you would refer to a class. This ability includes when you declare a reference variable, or cast from one type to another, as shown in Listing 18.
Listing 18. Assigning a new Manager instance to a StockOptionEligible reference
package com.makotojava.intro;
import java.math.BigDecimal;
import org.junit.Test;
public class ManagerTest {
  @Test
  public void testCalculateAndAwardStockOptions() {
    StockOptionEligible soe = new Manager();// perfectly valid
    calculateAndAwardStockOptions(soe);
    calculateAndAwardStockOptions(new Manager());// works too
    }
    public static void calculateAndAwardStockOptions(StockOptionEligible soe) {
    BigDecimal reallyCheapPrice = BigDecimal.valueOf(0.01);
    int numberOfOptions = 10000;
    soe.awardStockOptions(numberOfOptions, reallyCheapPrice);
  }
}
As you can see, it's valid to assign a new Manager instance to a StockOptionEligible reference, and to pass a new Manager instance to a method that expects a StockOptionEligible reference.

Assignments: Interfaces

You can assign a reference from a class that implements an interface to a variable of an interface type, but certain rules apply. From Listing 18, you can see that assigning a Manager instance to a StockOptionEligible variable reference is valid. The reason is that the Manager class implements that interface. However, the following assignment would not be valid:
Manager m = new Manager();
 StockOptionEligible soe = m; //okay
 Employee e = soe; // Wrong!
Because Employee is a supertype of Manager, this code might at first seem okay, but it's not. Why not? Because Manager implements the StockOptionEligible interface, whereas Employee does not.
Assignments such as these follow the rules of assignment that you saw in the Inheritance section. And as with classes, you can only assign an interface reference to a variable of the same type or a superinterface type.

Previous Post
Next Post

post written by:

0 coment�rios: