I will illustrate my issue with the use of an example:
The addActionListener method accepts an ActionListener Interface as its only argument.
So when invoking that method on an object/component (such as a Button) in order to register a listener to the object, through the use of an anonymous inner class, why is it that we also need to implement the Interface class? Is it because by definition, interfaces cannot be instantiated, unless of course you are creating an object of that Interface type that implements the abstract methods of that Interface?
i.e.
aButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do stuff
}
});
That is, through the use of anonymous classes, we can avoid explicitly making the entire class implementing the interface (as declared in the header), but rather we are instantiating an object of the Interface (which by definition of an Interface shouldn't be possible) and implementing the Interface's abstract methods within the anonymous class.
So it is only possible to instantiate an object the Interface due to the fact that at that point in time, a contract needs to be fulfilled to implement the Interface's methods, and in doing so, allows us to make an object from the Interface?
Therefore, is the reason why we can implement the actionPerformed() method of the Interface only possible because of the fact that we had instantiated an object from the Interface (which simultaneously requires us to fulfil the contract of implementing the abstract methods)? So could it be said that we are 'implicitly' implementing an interface by the in-situ instantiation of the Interface (as the addActionListener argument)?
You are not instantiating the interface.
You are defining and instantiating an actual, concrete class that implements the interface. You need to implement every method declared in the interface, just as if you wrote a "normal" class implementing the interface.
The anonymous class construct saves you the trouble of having to name a class that is only going to be used in one very specific place in your code. But if you wanted to you could have decided to do that. Under the covers it is the same thing -- you have defined a class to implement the interface and then instantiated that class.
Related
I have an interface myInterface which defines two methods, method1, method2. This interface is being implemented by 100 other classes. My requirement is that I am able to to add a field to the interface which is unique to each class. Example: I want to add a field numberOfRequests, which is unique for all classes. So everytime I call method1, I can update numberOfRequests for that class. How do I achieve this by making changes at interface level?
It is not possible to define instance (non-static) fields in interfaces. You can only add a static field to the interface, which then only belongs directly to this interface.
To implement the required functionality, you have to add this field to every single class that implements the interface.
If you are not restricted to using an interface, you can make all implementing classes extending a new class which has the numberOfRequests field. This new class could then also implement this interface, if the behaviour all the methods accessing numberOfRequests is always the same in all implementing classes.
I'm 13 and quite new to java. What I can't seem to figure out is how NOT to implement overriding methods in a class from an interface because they are references. I don't want to make a new copy, and I can't just make (insert Class here) extend (the class the interface gets some of its methods from). So I implement it and what do i get?
err: The type Threadmanager must implement the inherited abstract method (the method)
and then it has a list, one of which says "implement uninherited methods".
But I dont want to implement any methods! I want to use them!
Threadmanager tm;
AwtUtils manager = tm;
manager.drawImage(/*params*/)
The above is what i want, the following is what i don't want:
#override
public void drawImage(/*params*/){
...
}
I don't want to redefine the methods in the interface, simply just use them. and I cant have class ThreadManager extends Debugger(.java) because it already extends something. I thought interfaces were a way you could use those methods in another class without inheriting them through "class foo extends bar"
By the way, all the methods referenced in the interface are references to methods in my class Debugger.java which doubles up as a debugger and the game library.
You cannot use methods from an interface. An interface has no code, only definitions. Think of it as a functionality contract that classes implementing it have to fulfill.
For example
public interface Example {
public void method1ToImplement();
public int method2ToImplement(final String input);
}
This is a contract that all classes implementing this interface must fulfill. This means any instantiable class that implements Example has to implement public void method1ToImplement() and public int method2ToImplement(String). This is because you're stating this class fulfills this functionality, so you must implement this funcionality because as of now there's no code for this functionality in your class since the interface contains no code. For example, you cannot use the methods in List, in fact you cannot even create a new List because it's an interface. But you can create and ArrayList and use its methods because it's a non-abstract class implementing the List interface.
Maybe you're confused because you saw somewhere else you can use already implemented methods, for example toString() (which is already implemented in all classes). This is because this method is not defined in an interface but by a parent class (in case of toString() it's Object that implements it).
TL;DR: A class implementing an interface must implement its methods unless it's abstract.
If I'm understanding you right, you want a class to implement an interface, but don't implement its methods. If that's so, you cannot. Implementation of interface methods is mandatory, unless you're writing an abstract class.
I'm guessing there's something missing on your question, so please, provide some code of your Interface and Class so that we could give you a better answer.
I think you're confused about what an interface does. An interface simply defines a contract such that any object which implements the interface must define the methods in the interface. If you have an abstract class, then you must implement the abstract methods of said class for any class that extends the abstract class. The only exception to this is when you extend from a class that has already implemented the abstract methods or interface and you don't want/need to redefine them for subclasses.
You say that you don't want to implement the methods, you just want to use them, but you can't use methods that don't exist. Implementing an interface does not magically define the logic in the methods in the interface--that is your job. Again, it simply states that any objects that implement the interface will have the interfaces' methods defined.
One of the nice things about interfaces is the following: Let's assume that we have a collection of objects that all implement a particular interface, then we can call any method from the interface on all those objects. NB: we can group said objects together by having an array, ArrayList, or what have you that take the interface as the type parameter, ie ArrayList<MyInterface>
More specific example:
Let's consider a Shape interface that solely includes the header for an area method. We can have a bunch of difference types of shapes that implement the Shape interface (circles, squares, etc). In each shape class, we define a method to get the area for said shape. Now, if we have an ArrayList<Shape> shapes =... we can put different types of shapes into that list and do the following:
for (Shape s : shapes)
{
System.out.println(s.area());
}
As I know the subclass constructor calls the super class constructor by using super();.
But since interface doesn't have any constructor, how can inheritance take place?
But since interface doesn't have any constructor how can inheritance take place??
Easy, an interface cannot have any instance fields so there is nothing to construct. You cannot place in code in an interface (up to Java 7 anyway) so there is nothing which needs to be called.
The interface is a contract, defining what methods mush be offered by the implementation. A class doesn't inherit an interface but implements it.
From the specification :
This type has no implementation, but otherwise unrelated classes can
implement it by providing implementations for its abstract methods.
Interfaces (also known as Service Contracts) are implemented, not constructed. They define a set of methods (Services) that a class provides, so a client knows what can he expect of the implementing class regardless of the actual type implementing the interface. The constructor is related to this particular instance of a given type, implementing the interface.
IYourObject yourObject = new YourObject();
On the other hand, interface inheritance is also by extension. It "adds" the methods of an interface to another one and allow the possibility of switching the interface type of an object amongst the different interfaces in the "hierarchy".
Interface is not inherited - it is rather implemented
Interface doesn't contain constructor because of the following reasons:
The data member of the interface are already initialized .
Constructors of the special defined methods which are not permitted to defined and moreover interface data member are static.
In java, we give body to an abstract method of parent class inside the child class and then call that function via child class object like:
//let the abstract function be fun then,
child c= new child();
c.fun();
then fun executes the body given by child but what's new in this as same being done in function overriding?
The difference is that subclasses that won't also be abstract must implement all inherited abstract methods. Also, the concrete implementation can't call super.method() as there's no implementation in the abstract class.
As to the why, or perhaps more explicitly, why choose the abstract superclass rather than an interface: often it's useful to provide implementations of only some methods of an interface - for instance for code-sharing - and require concrete subclasses to provide specific implementations for other parts of the interface.
The abstraction means that the developer has (explicit) to implement the method. Overriding means that the developer implement a method that's already implement. This is by definition of the languaje.
Is there any keyword or design pattern for doing this?
Please check the update
public abstract class Root
{
public abstract void foo();
}
public abstract class SubClass extends Root
{
public void foo()
{
// Do something
//---------------- Update -------------------//
// This method contains important code
// that is needed when I'm using a instance
// of SubClass and it is no instance of any
// other class extending SubClass
}
}
public class SubberClass extends SubClass
{
// Here is it not necessary to override foo()
// So is there a way to make this necessary?
// A way to obligate the developer make again the override
}
Thanks
If you are doing this, then you are probably abusing inheritance; inheritance, contrary to popular myth, is not intended for making custom hooks/handlers, but rather to enable alternative implementations.
If you want your user to provide some sort of function/hook/callback, then you should define an interface that provides just those methods that you need your user to define. Then you should require the user to pass in an instance of that interface to your object's constructor or passed into the function that needs it.
Aggregation, delegation, and composition are frequently better and safer design patterns than inheritance; forcing other users to inherit from your class, is incredibly risky, as it provides the user with many opportunities to violate the contract of your class or to invalidate the invariant of your base class.
If every class subclassing SubClass has to override foo() then why provide an implementation at all in SubClass? You can simply remove the method definition from SubClass and then all subclasses will be forced to provide an implementation.
If you really want to, you can re-declare foo as abstract.
public abstract class SubberClass extends SubClass
{
public abstract void foo();
}
Instead of overriding foo() in SubClass, create a new method fooImpl() and leave foo() abstract. This way, all classes must implement foo() but you can simply implement it by calling fooImpl() if that is already enough.
Yeah it is not necessary to override foo() in SubberClass.
You can't have it both ways. You can't provide a method with a default implementation AND require child classes override it. Instead of declaring the method as abstract in Root, you could define an interface (IFoo) with the method declared and then provide an abstract class that implements the interface. That would still require a concrete child class but would not require a method override.
Most of the time you see this type of pattern, an interface is used to define a set of methods and an abstract base class provides some default implementations for some but not all methods from the interface. This requires the concrete child class to provide code for the remaining methods and the option to override the default behaviors.
In any case, you can't provide a default behavior for a single method and require child classes to override that same method.