Interface initialization?

In the current problem I have ( printing a file to a physical printer in Java ). I execute the code like crazy trying to absorb any useful missing information from the javadoc of each class used.

Now I pulled this code from the previous questions, so there was an honest bit that I didn't write myself. The problem I noticed is that the code I grab initializes an object, say, "SimpleDoc", which implements an interface (Doc) and assigns it to that interface ?!

A small piece of code:

Doc mydoc = new SimpleDoc(textStream, flavor, null); 

Now, as I understand it, in java we create objects. I am familiar with inheritance, and I am familiar with the trick of using interfaces to let a class “inherit” several superclasses.

But it just doesn't stick. You can create a class that implements the interface, and that's fine with me. But what happens when an interface is created and the object is reduced to its interface? What do I get when I access mydoc for sure?

+8
java object initialization interface netbeans
source share
2 answers

The trick is to understand that you are not “creating,” “instantiating,” or “initializing” the interface. You simply define a variable as something that you know implements this interface.

In essence, you are telling other programmers working on this code that for the rest of this method, you are only interested in the fact that myDoc is a Doc (that is, that satisfies the Doc interface). This will make programming easier, because the autocomplete IDE will now only show the methods defined by this interface, and not all that SimpleDoc can do.

Imagine that in the future you want to expand your functionality to have different Doc implementations depending on the input. Instead of explicitly creating a SimpleDoc, you say:

 Doc mydoc = docFactory.getByType(inputType); 

docFactory can generate any type of Doc , and this method does not really care about which type is created, because it will treat it as a Doc independently.

+5
source share

You cannot create interfaces, here you create the mydoc object of the mydoc class, which implements the Doc interface. Since the class implements this interface, you can handle mydoc as if it were an instance of this interface. This allows you to access all the declared methods in the interface that are implemented in the SimpleDoc class

If, for example, your Doc interface looks like this:

 public interface Doc { void print(); } 

and your SimpleDoc class will look like this:

 public class SimpleDoc implements Doc { public void clear() { ... } @Override public void print() { ... } } 

... then you can only access the print() throws from you mydoc object. But you can also say:

 SimpleDoc mydoc = new SimpleDoc(); 

... and then you can also call clear()

+4
source share

All Articles