How to use an abstract iterator (of the la4j library)? - java

It's a bit hard to phrase my question. I'm struggling a lot with using libraries in java currently and often are not really sure how to efficiently use them. In theory I know what an interface and an abstract class is but it seems that in practice these things are hard for me to use.
So, to be more specific, as an example, in the moment I'm using a CCS matrix from the la4j library. I now want to iterate over it (the rows and every entry in each of these rows) and want to use the library for it but I find only abstract iterators (e.g. the RowMajorMatrixIterator). In general: I don't know what to do with abstract classes (or interfaces) from libraries. Specifically in this moment and as a typical instance of my problem: If I have this abstract iterator, how do I actually use it (for my CCS Matrix)?
Every help is appreciated!

You get the iterators from the matrices you created beforehand: the class Matrix defines a method rowMajorIterator(), for example, so you can do
RowMajorMatrixIterator it = yourMatrix.rowMajorIterator();
This pattern is called "Factory Method".
As Thomas points out, it is often implemented as some sort of inner class, like this:
public class MyMatrix extends Matrix {
public RowMajorIterator rowMajorIterator() {
return new RowMajorIterator() { // anonymous class
// needs to implement the abstract methods
public int get() { ... }
...
}
}
}
or
public class MyMatrix extends Matrix {
public RowMajorIterator rowMajorIterator() {
return new MyRowMajorIterator();
}
class MyRowMajorIterator extends RowMajorIterator { // inner, named class
// needs to implement the abstract methods
public int get() { ... }
...
}
}
These inner classes have access to the members of the "outer" class Matrix.

Related

Access the same method among different classes?

I am programming a simple platformer game, and I have several types of platforms. I created a class for the most simple type and made the rest subclasses, with the only difference between each class being the value of their variables (so they all share the same variable and method names).
In my collision detection, I loop through a HashMap. Within that HashMap are ArrayLists of the instances of each class. But when I use a nested loop to loop through try to call their methods implicitly, I have found that I cannot access these methods without explicitly declaring which class I want to call the method from.
I have done research, although the only way I can see of doing this is to loop through the instances of each class separately, meaning one loop per class; I would rather not do this, since it would be a lot more code than I feel is necessary.
In order to be able to call a common method on classes of different types you need to give your objects a common supertype declaring the common method - i.e. they should have a common superclass, or implement a common interface.
Interfaces provide an easier way of declaring common functionality, because a class can implement multiple interfaces, but it can extend only one class.
Provide an interface with the common method, then declare the map to use objects of that interface, i.e.
interface CommonInterface {
void commonMethod(int arg);
}
class One implements CommonInterface {
public void commonMethod(int arg) {
...
}
}
class Two implements CommonInterface {
public void commonMethod(int arg) {
...
}
}
Here is what you can do now:
Map<String,CommonInterface> myMap = new HashMap<>();
myMap.put("one", new One());
myMap.put("two", new Two());
for (Map.Entry<String,CommonInterface> e : myMap.entrySet()) {
System.out.println(e.getKey());
CommonInterface c = e.getValue();
c.commonMethod(123);
}
Simple, make each platform class implement an IPlatform interface or extand a base class. Look up java polymorphism and interfaces.
Are your subclasses overriding the common methods from the super class?
In other words, are your subclass' common methods declared in your simpler class?
If it is the case, you can simply call the method as if it is a simple class:
public abstract class Fruit {
public abstract void method();
}
public class Apple extends Fruit {
#Override
public void method() {
System.out.println("I'm an apple");
}
}
public class Orange extends Fruit {
#Override
public void method()
System.out.println("I'm an orange");
}
}
Using this you can simply call your method from any fruit, since it has your method declared. No need to know which fruit it is. The following code:
Fruit fruit = new Orange();
fruit.method();
will output: "I'm an orange".

use of abstract class containing non-abstract methods only

There is an abstract class containing non-abstract methods only. Now I create another class which extends abstract class. For ex :
abstract class Parent{
void No(){
System.out.println("abcd");
}
}
class Child extends Parent {
}
Instead of abstract class, I could have create another class. What is use of making this above class as an Abstract ?
I guess what you want to know is if in this case it make any difference not to make abstract:
No it doesn't: as long as you do not have abstract methods, you can use abstract or non-abstract classes (even if abstract makes no sense in this case). But if you've one abstract method, you class needs to be marked as abstract.
an abstract class without any abstract methods sometimes is a design decision. for example, a regular expression can be implemented like this:
public abstract class Regex {
private Regex(String pattern) { /* do something */ }
private static class ConcreteRegex {
private ConcreteRegex(String pattern) {
super(pattern);
}
}
private static final int MAX_CACHE_SIZE = 100;
private static Object cacheLock = new Object();
private static Queue<String> patternq = new LinkedList<>();
private static Map<String, Regex> cache = new HashMap<>();
private static Regex checkCache(String pattern) {
synchronized(cacheLock) {
return cache.get(pattern);
}
}
private static void insertCache(String pattern, Regex regex) {
synchronized(cacheLock) {
patternq.offer(pattern);
cache.put(pattern, regex);
while(patternq.size() >= MAX_CACHE_SIZE) {
String key = patternq.poll();
cache.remove(key);
}
}
}
public static Regex compile(String pattern) {
Regex result = checkCache(pattern);
if (result == null) {
Regex compiled = new ConcreteRegex(pattern);
insertCache(pattern, compiled);
return compiled;
}
return result;
}
public static Matcher match(String pattern, String str) {
Regex result = compile(pattern);
return result.matches(str);
}
// define find, findall, and so on like this
}
so what's the point to do all these work? well, sometimes it would be quite handy to have these methods to shorten the program, while it may have a chance to increase the performance of the program. by doing this, we need to prevent user to call the constructor directly. but why not have these caching management inside of the constructor?
well, this is not recommended(it will compile though), since you are leaking the instance out in the middle of instantiation, such that there is a chance to reference the partially instantiated object, which may generally be considered as a dangerous behavior.
of course, there are other cases where you decide to have such "weird" abstract classes, which are too many to enumerate.
It's true that if an abstract class has no abstract methods, then there's nothing that forcibly prevents would-be clients from creating a trivial child class and instantiating it; but keep in mind that we write code to be read and understood, not just by the compiler, but by other programmers (including our future selves). We cannot forcibly prevent those programmers from messing up; but we can write code that helps them do the right thing.
So the question is — what is a situation where a class has no abstract methods, but where it nonetheless doesn't make sense to instantiate it directly?
There are a few possibilities that come to mind, but I'll just mention one.
Consider an interface like java.util.List, where many of the methods are convenience methods that can be defined in terms of others. In particular, the methods that use iterators can be defined in terms of the methods that use indices, and vice versa.
One could easily imagine an abstract List implementation that defines all of these methods, but in terms of each other. You could then easily implement List by subclassing this implementation and overriding either an iterator-y method or an index-y method.
(As it happens, this is not the approach the JDK takes. The JDK instead offers two abstract implementations, java.util.AbstractList and java.util.AbstractSequentialList, each of which has some abstract methods for the subclass to fill in. I think the JDK's approach is superior, because it makes it clearer what you are supposed to do, and generates a compile-error where the combined-abstract-class approach generates a StackOverflowError at runtime. But I would not fault the developer who, with a surfeit of DRY, took the combined-abstract-class approach.)
One advantage I see is that you prevent people instantiate it.
For example you want to make a system of vehicle. In the parent abstract class, there is only one method run(){}, well, not abstract. You want to instantiate it as VW, TOYOTA OR Ford, but not a non-specified brand vehicle. You inherent vehicle class as non abstract class VW, Toyota or Ford. but you couldn't start with vehicle, cuz it's more like a "type", not something you want to build.

how to instance generic abstract class

I am trying to profile a ann algorithm written in Java that is implemented as a generic abstract class and I cant figure out how to instance it.
Eclipse gives me error "Cannot instantiate the type KdTree" which is not very helpful. Any ideas on how to instance this class so I can test it?
Class defination and constructor:
public abstract class KdTree<T> {
private KdTree(int dimensions, Integer sizeLimit) {
this.dimensions = dimensions;
}
}
My attempt to instance it:
public class test_robo {
public void run_test()
{
KdTree<Integer> tree = new KdTree<Integer>(1,1);
}
}
link to the full code for KdTree
http://robowiki.net/wiki/User:Rednaxela/kD-Tree
First of all, you cannot instantiate an abstract class.
I saw the code in the link you provided; there are few implementations of the base class KdTree<T> already in there.
WeightedSqrEuclid
WeightedManhattan
...
If that's not what you're looking for, extend the base class and implement all those abstract methods as you wish.
You cannot instantiate an abstract class directly. The reason it is declared abstract is that it is not meant to be used by itself - you have to provide an implementation of its abstract methods first.
You need to inherit your own class from the abstract base, implement its abstract methods, and then instantiate your class. An instance of your class is automatically an instance of its abstract base.
public class ProfilerTree extends KdTree<Integer> {
public ProfilerTree(int dimensions, Integer sizeLimit) {
super(dimensions, sizeLimit);
}
...
// Implement abstract methods of KdTree<Integer> here
}
...
KdTree<Integer> tree = new ProfilerTree(1,1);
you can't instantiate an abstract class. Abstract actually means it doesn't make sense on its own so it always has to be extended and its methods implemented.
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).
see http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can instantiate it by constructing an anonymous subclass, like so:
KdTree<Integer> tree = new KdTree<Integer>(1,1)
{
#Override
public void myAbstractMethodName()
{
//do something!
}
};
Otherwise, you can generate your own implementation:
private class KdTreeSub extends KdTree<Integer>
{
public KdTreeSub()
{
super(1, 1);
}
}
And later call it
public void myMethod()
{
...
KdTree<Integer> kdtree = new KdTreeSub();
...
}
The reason for this is that abstract classes are not complete classes. They are missing parts of them, usually a method. This method is marked with the "abstract" identifier:
public abstract int read();
The idea behind this is that you can construct a class that handles other parts:
public byte[] read(int len)
{
byte[] b = new byte[len];
for(int i = 0; i < b.length; i++) b[i] = read();
return b;
}
And simplify creating new classes.
The class, as it stands, was not meant to be instantiated. It's meant to store boilerplate code for concrete implementations. There are 4 of them in your link, starting with WeightedSqrEuclid.
You can either instantiate those, simply by e.g. new WeightedSqrEuclid<Integer>(1,1), or, if you want to profile the general code, write your own class extending KdTree.
However, in the latter case you should either create your subclass in the same file, or change a constructor of KdTree to at least protected. This is because, to create a subclass of this type, you need to call one of the constructors of KdTree in your implementation.

Calling super class method inside implemented abstract method

Basicaly I have a need for several methods that do the same thing but with different parameters the sub-classes can chose from, and still force the implementation.
Is this a correct approach/design ?
EDIT: I have edited the addItem() body, these methods contain the final logic that is used to handle the passed parameters
public abstract Class A {
public abstract void addItemImpl()
addItem(String s) {
// do stuff
}
addItem(Collection c) {
// do stuff
}
addItem(Item item) {
// do stuff
}
}
public Class B extends A {
addItemImpl() {
addItem("text, text2")
}
}
public Class C extends A {
addItemImpl() {
addItem([item, item2])
}
}
No, this will not work.
You will not be able to define the "doStuff()" method because you have to handle the parameters. You provide not enough information to give you detailed help. But it's possible that generics might come in handy:
public abstract Class A<T> {
public addItem(T t) {
// dostuff with t
}
}
public Class B extends A<String> {
}
public Class C extends A<Collection> {
}
This is a perfect case for: Favor composition over inheritance.
Your subclasses don't fully benefit from the superclass and don't depend on its implementation details. Then define an interface for the contract B and C must obey (addItemImpl()) and compose them with A.
Ask yourself: is B really an A? is C really and A?
What you have is technically correct, but with out knowing what addItem actually does it is difficult to know if this is the best solution. My guess would be that there probably is a better way.
If addItem essentially set values to be used in the doStuff, I would just do that work in the Class B and C instead. Any others that need to do it the same way as B could extend it instead of A.
Edit: Based on your edit, I would say this is probably a bad example to use an abstract class. There is no truely shared functionality. An interface would be more appropriate as you need a different implementation for each. You are just trying to hide that inside an abstract class. I would change A to an interface along with using generics.
Only go the abstract class route if there is actually shared code that is exactly the same in all the classes without having to do any tricks to make it work (like above).
If you need force implementation for few methods, then Abstract methods are ideal.
But be careful only the very first Non-Abstract sub-class of the Super-class is bound to implement all the abstract methods in it....

Is there more to an interface than having the correct methods

So lets say I have this interface:
public interface IBox
{
public void setSize(int size);
public int getSize();
public int getArea();
//...and so on
}
And I have a class that implements it:
public class Rectangle implements IBox
{
private int size;
//Methods here
}
If I wanted to use the interface IBox, i can't actually create an instance of it, in the way:
public static void main(String args[])
{
Ibox myBox=new Ibox();
}
right? So I'd actually have to do this:
public static void main(String args[])
{
Rectangle myBox=new Rectangle();
}
If that's true, then the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?
Interfaces are a way to make your code more flexible. What you do is this:
Ibox myBox=new Rectangle();
Then, later, if you decide you want to use a different kind of box (maybe there's another library, with a better kind of box), you switch your code to:
Ibox myBox=new OtherKindOfBox();
Once you get used to it, you'll find it's a great (actually essential) way to work.
Another reason is, for example, if you want to create a list of boxes and perform some operation on each one, but you want the list to contain different kinds of boxes. On each box you could do:
myBox.close()
(assuming IBox has a close() method) even though the actual class of myBox changes depending on which box you're at in the iteration.
What makes interfaces useful is not the fact that "you can change your mind and use a different implementation later and only have to change the one place where the object is created". That's a non-issue.
The real point is already in the name: they define an interface that anyone at all can implement to use all code that operates on that interface. The best example is java.util.Collections which provides all kinds of useful methods that operate exclusively on interfaces, such as sort() or reverse() for List. The point here is that this code can now be used to sort or reverse any class that implements the List interfaces - not just ArrayList and LinkedList, but also classes that you write yourself, which may be implemented in a way the people who wrote java.util.Collections never imagined.
In the same way, you can write code that operates on well-known interfaces, or interfaces you define, and other people can use your code without having to ask you to support their classes.
Another common use of interfaces is for Callbacks. For example, java.swing.table.TableCellRenderer, which allows you to influence how a Swing table displays the data in a certain column. You implement that interface, pass an instance to the JTable, and at some point during the rendering of the table, your code will get called to do its stuff.
One of the many uses I have read is where its difficult without multiple-inheritance-using-interfaces in Java :
class Animal
{
void walk() { }
....
.... //other methods and finally
void chew() { } //concentrate on this
}
Now, Imagine a case where:
class Reptile extends Animal
{
//reptile specific code here
} //not a problem here
but,
class Bird extends Animal
{
...... //other Bird specific code
} //now Birds cannot chew so this would a problem in the sense Bird classes can also call chew() method which is unwanted
Better design would be:
class Animal
{
void walk() { }
....
.... //other methods
}
Animal does not have the chew() method and instead is put in an interface as :
interface Chewable {
void chew();
}
and have Reptile class implement this and not Birds (since Birds cannot chew) :
class Reptile extends Animal implements Chewable { }
and incase of Birds simply:
class Bird extends Animal { }
The purpose of interfaces is polymorphism, a.k.a. type substitution. For example, given the following method:
public void scale(IBox b, int i) {
b.setSize(b.getSize() * i);
}
When calling the scale method, you can provide any value that is of a type that implements the IBox interface. In other words, if Rectangle and Square both implement IBox, you can provide either a Rectangle or a Square wherever an IBox is expected.
Interfaces allow statically typed languages to support polymorphism. An Object Oriented purist would insist that a language should provide inheritance, encapsulation, modularity and polymorphism in order to be a fully-featured Object Oriented language. In dynamically-typed - or duck typed - languages (like Smalltalk,) polymorphism is trivial; however, in statically typed languages (like Java or C#,) polymorphism is far from trivial (in fact, on the surface it seems to be at odds with the notion of strong typing.)
Let me demonstrate:
In a dynamically-typed (or duck typed) language (like Smalltalk), all variables are references to objects (nothing less and nothing more.) So, in Smalltalk, I can do this:
|anAnimal|
anAnimal := Pig new.
anAnimal makeNoise.
anAnimal := Cow new.
anAnimal makeNoise.
That code:
Declares a local variable called anAnimal (note that we DO NOT specify the TYPE of the variable - all variables are references to an object, no more and no less.)
Creates a new instance of the class named "Pig"
Assigns that new instance of Pig to the variable anAnimal.
Sends the message makeNoise to the pig.
Repeats the whole thing using a cow, but assigning it to the same exact variable as the Pig.
The same Java code would look something like this (making the assumption that Duck and Cow are subclasses of Animal:
Animal anAnimal = new Pig();
duck.makeNoise();
anAnimal = new Cow();
cow.makeNoise();
That's all well and good, until we introduce class Vegetable. Vegetables have some of the same behavior as Animal, but not all. For example, both Animal and Vegetable might be able to grow, but clearly vegetables don't make noise and animals cannot be harvested.
In Smalltalk, we can write this:
|aFarmObject|
aFarmObject := Cow new.
aFarmObject grow.
aFarmObject makeNoise.
aFarmObject := Corn new.
aFarmObject grow.
aFarmObject harvest.
This works perfectly well in Smalltalk because it is duck-typed (if it walks like a duck, and quacks like a duck - it is a duck.) In this case, when a message is sent to an object, a lookup is performed on the receiver's method list, and if a matching method is found, it is called. If not, some kind of NoSuchMethodError exception is thrown - but it's all done at runtime.
But in Java, a statically typed language, what type can we assign to our variable? Corn needs to inherit from Vegetable, to support grow, but cannot inherit from Animal, because it does not make noise. Cow needs to inherit from Animal to support makeNoise, but cannot inherit from Vegetable because it should not implement harvest. It looks like we need multiple inheritance - the ability to inherit from more than one class. But that turns out to be a pretty difficult language feature because of all the edge cases that pop up (what happens when more than one parallel superclass implement the same method?, etc.)
Along come interfaces...
If we make Animal and Vegetable classes, with each implementing Growable, we can declare that our Cow is Animal and our Corn is Vegetable. We can also declare that both Animal and Vegetable are Growable. That lets us write this to grow everything:
List<Growable> list = new ArrayList<Growable>();
list.add(new Cow());
list.add(new Corn());
list.add(new Pig());
for(Growable g : list) {
g.grow();
}
And it lets us do this, to make animal noises:
List<Animal> list = new ArrayList<Animal>();
list.add(new Cow());
list.add(new Pig());
for(Animal a : list) {
a.makeNoise();
}
The advantage to the duck-typed language is that you get really nice polymorphism: all a class has to do to provide behavior is provide the method. As long as everyone plays nice, and only sends messages that match defined methods, all is good. The downside is that the kind of error below isn't caught until runtime:
|aFarmObject|
aFarmObject := Corn new.
aFarmObject makeNoise. // No compiler error - not checked until runtime.
Statically-typed languages provide much better "programming by contract," because they will catch the two kinds of error below at compile-time:
// Compiler error: Corn cannot be cast to Animal.
Animal farmObject = new Corn();
farmObject makeNoise();
--
// Compiler error: Animal doesn't have the harvest message.
Animal farmObject = new Cow();
farmObject.harvest();
So....to summarize:
Interface implementation allows you to specify what kinds of things objects can do (interaction) and Class inheritance lets you specify how things should be done (implementation).
Interfaces give us many of the benefits of "true" polymorphism, without sacrificing compiler type checking.
Normally Interfaces define the interface you should use (as the name says it ;-) ). Sample
public void foo(List l) {
... do something
}
Now your function foo accepts ArrayLists, LinkedLists, ... not only one type.
The most important thing in Java is that you can implement multiple interfaces but you can only extend ONE class! Sample:
class Test extends Foo implements Comparable, Serializable, Formattable {
...
}
is possible but
class Test extends Foo, Bar, Buz {
...
}
is not!
Your code above could also be: IBox myBox = new Rectangle();. The important thing is now, that myBox ONLY contains the methods/fields from IBox and not the (possibly existing) other methods from Rectangle.
I think you understand everything Interfaces do, but you're not yet imagining the situations in which an Interface is useful.
If you're instantiating, using and releasing an object all within a narrow scope (for example, within one method call), an Interface doesn't really add anything. Like you noted, the concrete class is known.
Where Interfaces are useful is when an object needs to be created one place and returned to a caller that may not care about the implementation details. Let's change your IBox example to an Shape. Now we can have implementations of Shape such as Rectangle, Circle, Triangle, etc., The implementations of the getArea() and getSize() methods will be completely different for each concrete class.
Now you can use a factory with a variety of createShape(params) methods which will return an appropriate Shape depending on the params passed in. Obviously, the factory will know about what type of Shape is being created, but the caller won't have to care about whether it's a circle, or a square, or so on.
Now, imagine you have a variety of operations you have to perform on your shapes. Maybe you need to sort them by area, set them all to a new size, and then display them in a UI. The Shapes are all created by the factory and then can be passed to the Sorter, Sizer and Display classes very easily. If you need to add a hexagon class some time in the future, you don't have to change anything but the factory. Without the Interface, adding another shape becomes a very messy process.
you could do
Ibox myBox = new Rectangle();
that way you are using this object as Ibox and you don't care that its really Rectangle .
WHY INTERFACE??????
It starts with a dog. In particular, a pug.
The pug has various behaviors:
public class Pug {
private String name;
public Pug(String n) { name = n; }
public String getName() { return name; }
public String bark() { return "Arf!"; }
public boolean hasCurlyTail() { return true; } }
And you have a Labrador, who also has a set of behaviors.
public class Lab {
private String name;
public Lab(String n) { name = n; }
public String getName() { return name; }
public String bark() { return "Woof!"; }
public boolean hasCurlyTail() { return false; } }
We can make some pugs and labs:
Pug pug = new Pug("Spot");
Lab lab = new Lab("Fido");
And we can invoke their behaviors:
pug.bark() -> "Arf!"
lab.bark() -> "Woof!"
pug.hasCurlyTail() -> true
lab.hasCurlyTail() -> false
pug.getName() -> "Spot"
Let's say I run a dog kennel and I need to keep track of all the dogs I'm housing. I need to store my pugs and labradors in separate arrays:
public class Kennel {
Pug[] pugs = new Pug[10];
Lab[] labs = new Lab[10];
public void addPug(Pug p) { ... }
public void addLab(Lab l) { ... }
public void printDogs() { // Display names of all the dogs } }
But this is clearly not optimal. If I want to house some poodles, too, I have to change my Kennel definition to add an array of Poodles. In fact, I need a separate array for each kind of dog.
Insight: both pugs and labradors (and poodles) are types of dogs and they have the same set of behaviors. That is, we can say (for the purposes of this example) that all dogs can bark, have a name, and may or may not have a curly tail. We can use an interface to define what all dogs can do, but leave it up to the specific types of dogs to implement those particular behaviors. The interface says "here are the things that all dogs can do" but doesn't say how each behavior is done.
public interface Dog
{
public String bark();
public String getName();
public boolean hasCurlyTail(); }
Then I slightly alter the Pug and Lab classes to implement the Dog behaviors. We can say that a Pug is a Dog and a Lab is a dog.
public class Pug implements Dog {
// the rest is the same as before }
public class Lab implements Dog {
// the rest is the same as before
}
I can still instantiate Pugs and Labs as I previously did, but now I also get a new way to do it:
Dog d1 = new Pug("Spot");
Dog d2 = new Lab("Fido");
This says that d1 is not only a Dog, it's specifically a Pug. And d2 is also a Dog, specifically a Lab.
We can invoke the behaviors and they work as before:
d1.bark() -> "Arf!"
d2.bark() -> "Woof!"
d1.hasCurlyTail() -> true
d2.hasCurlyTail() -> false
d1.getName() -> "Spot"
Here's where all the extra work pays off. The Kennel class become much simpler. I need only one array and one addDog method. Both will work with any object that is a dog; that is, objects that implement the Dog interface.
public class Kennel {
Dog[] dogs = new Dog[20];
public void addDog(Dog d) { ... }
public void printDogs() {
// Display names of all the dogs } }
Here's how to use it:
Kennel k = new Kennel();
Dog d1 = new Pug("Spot");
Dog d2 = new Lab("Fido");
k.addDog(d1);
k.addDog(d2);
k.printDogs();
The last statement would display:
Spot Fido
An interface give you the ability to specify a set of behaviors that all classes that implement the interface will share in common. Consequently, we can define variables and collections (such as arrays) that don't have to know in advance what kind of specific object they will hold, only that they'll hold objects that implement the interface.
A great example of how interfaces are used is in the Collections framework. If you write a function that takes a List, then it doesn't matter if the user passes in a Vector or an ArrayList or a HashList or whatever. And you can pass that List to any function requiring a Collection or Iterable interface too.
This makes functions like Collections.sort(List list) possible, regardless of how the List is implemented.
This is the reason why Factory Patterns and other creational patterns are so popular in Java. You are correct that without them Java doesn't provide an out of the box mechanism for easy abstraction of instantiation. Still, you get abstraction everywhere where you don't create an object in your method, which should be most of your code.
As an aside, I generally encourage people to not follow the "IRealname" mechanism for naming interfaces. That's a Windows/COM thing that puts one foot in the grave of Hungarian notation and really isn't necessary (Java is already strongly typed, and the whole point of having interfaces is to have them as largely indistinguishable from class types as possible).
Don't forget that at a later date you can take an existing class, and make it implement IBox, and it will then become available to all your box-aware code.
This becomes a bit clearer if interfaces are named -able. e.g.
public interface Saveable {
....
public interface Printable {
....
etc. (Naming schemes don't always work e.g. I'm not sure Boxable is appropriate here)
the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?
I am updating the answer with new features of interface, which have introduced with java 8 version.
From oracle documentation page on summary of interface :
An interface declaration can contain
method signatures
default methods
static methods
constant definitions.
The only methods that have implementations are default and static methods.
Uses of interface:
To define a contract
To link unrelated classes with has a capabilities (e.g. classes implementing Serializable interface may or may not have any relation between them except implementing that interface
To provide interchangeable implementation e.g. strategy pattern
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces
Organize helper methods in your libraries with static methods ( you can keep static methods specific to an interface in the same interface rather than in a separate class)
Some related SE questions with respect to difference between abstract class and interface and use cases with working examples:
What is the difference between an interface and abstract class?
How should I have explained the difference between an Interface and an Abstract class?
Have a look at documentation page to understand new features added in java 8 : default methods and static methods.
The purpose of interfaces is abstraction, or decoupling from implementation.
If you introduce an abstraction in your program, you don't care about the possible implementations. You are interested in what it can do and not how, and you use an interface to express this in Java.
If you have CardboardBox and HtmlBox (both of which implement IBox), you can pass both of them to any method that accepts a IBox. Even though they are both very different and not completely interchangable, methods that don't care about "open" or "resize" can still use your classes (perhaps because they care about how many pixels are needed to display something on a screen).
Interfaces where a fetature added to java to allow multiple inheritance. The developers of Java though/realized that having multiple inheritance was a "dangerous" feature, that is why the came up with the idea of an interface.
multiple inheritance is dangerous because you might have a class like the following:
class Box{
public int getSize(){
return 0;
}
public int getArea(){
return 1;
}
}
class Triangle{
public int getSize(){
return 1;
}
public int getArea(){
return 0;
}
}
class FunckyFigure extends Box, Triable{
// we do not implement the methods we will used the inherited ones
}
Which would be the method that should be called when we use
FunckyFigure.GetArea();
All the problems are solved with interfaces, because you do know you can extend the interfaces and that they wont have classing methods... ofcourse the compiler is nice and tells you if you did not implemented a methods, but I like to think that is a side effect of a more interesting idea.
Here is my understanding of interface advantage. Correct me if I am wrong.
Imagine we are developing OS and other team is developing the drivers for some devices.
So we have developed an interface StorageDevice. We have two implementations of it (FDD and HDD) provided by other developers team.
Then we have a OperatingSystem class which can call interface methods such as saveData by just passing an instance of class implemented the StorageDevice interface.
The advantage here is that we don't care about the implementation of the interface. The other team will do the job by implementing the StorageDevice interface.
package mypack;
interface StorageDevice {
void saveData (String data);
}
class FDD implements StorageDevice {
public void saveData (String data) {
System.out.println("Save to floppy drive! Data: "+data);
}
}
class HDD implements StorageDevice {
public void saveData (String data) {
System.out.println("Save to hard disk drive! Data: "+data);
}
}
class OperatingSystem {
public String name;
StorageDevice[] devices;
public OperatingSystem(String name, StorageDevice[] devices) {
this.name = name;
this.devices = devices.clone();
System.out.println("Running OS " + this.name);
System.out.println("List with storage devices available:");
for (StorageDevice s: devices) {
System.out.println(s);
}
}
public void saveSomeDataToStorageDevice (StorageDevice storage, String data) {
storage.saveData(data);
}
}
public class Main {
public static void main(String[] args) {
StorageDevice fdd0 = new FDD();
StorageDevice hdd0 = new HDD();
StorageDevice[] devs = {fdd0, hdd0};
OperatingSystem os = new OperatingSystem("Linux", devs);
os.saveSomeDataToStorageDevice(fdd0, "blah, blah, blah...");
}
}

Categories