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.
Related
As I continue to expand my knowledge of OOP programming, it's becoming a bit more difficult to tie all the concepts back together. Separately, I know what an object, class, interface, and inheritance is. However, I fail to see "the big picture."
An object embodies a specific concept (class) and stores specific data to that class. It's an instance of a class, to be more specific.
A class defines the common set of attributes and behaviors among all objects of its class ("the template")
Interfaces are essentially a to-do list of method headers. It expects its children to implement these abstract methods. It does this in an attempt to create a standard way of doing something in unrelated classes (ex: compareTo() in Comparable)
Inheritance allows subclasses to extend the design space for objects by adding more functionality and behaviors while still retaining that of the superclass.
All these concepts affect the way objects interact with classes, but I fail to see how inheritance and interfaces have anything to do with objects. This is a rather conceptual question, but what exactly is this "big picture?" How do all these concepts affect the relationship between classes and objects?
Inheritance is the OO concept which has many types like Single, Hybrid etc. Java supports Multiple inheritance in the way of Interface. Interface allows you to define the behaviour or functionality in abstract level. It leaves the children to implement those behaviour or functionality. For eg(given in official docs): You can define the behaviour of a Bicycle like gearUp, gearDown, pedal, break, etc., and let the brands to implement their style and functionality. Below is the java doc link.
https://docs.oracle.com/javase/tutorial/java/concepts/interface.html
Inheritance in simple terms is to acquire the properties / behaviours of an other class. In order to achieve Inheritance we have to use a keyword extends in JAVA.
Class B extends Class A means Class B will act just like class A and all the methods and Variables in class A can be referred using class B also. ie. Whatever class A possesses it is shared by class B too.
Whereas Interface is a Type Definition Block (User-Defined). An abstract (incomplete) class can be called Interface. An Interface allows only Incomplete methods. In order to Inherit an Interface we have a keyword implements in JAVA. If a Class implements an Interface it is bound to contract.
That is: Either the class implementing the Interface should be declared abstract OR the class should over-ride the method in Interface and Complete it.( ie. provide method body).
Example:
Interface Car
{ public void display(); //Incomplete Method, Method has no Implementation.
}
class B implements Car
{ public void display()
{ System.out.println(“HI”);
} }
Here display method is over-rided and completed in class B. Hence no need to declare class B as abstract.
NOTE: Multiple Inheritance using class is not possible in JAVA. ie. A child class can extend or have only one parent class.
Multiple Inheritance is possible in JAVA using Interfaces. ie. An interface can extend more than one interface / implement more than one interface.
Interface Objects cannot be created, because it is incomplete.
Interface methods should be made non-static, because it is incomplete and should be over-rided in order to make it complete. If interface methods are static, it cannot be over-rided, because only one copy of static members are present and that is loaded during class loading.
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.
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());
}
An abstract class can have both abstract and non abstract methods. What is the point of having non abstract methods in the abstract class if a new object of the abstract class can't be created?
I know you can override the non-abstract method in a child class and then use it through the object of the child class. But if you are doing that, what is the need of having the non-abstract method with an implementation in the first place?
Think more or google more.
If your child classes have the common functionality then why you will override the method in every class? you can use the base class(which is abstract in this case) method.There comes the need of non-abtract(concrete as they called mostly) methods.
while having abstract method there(as you know already i think), we can override according to our requirement.
If you need all methods should be override in every child classes according to their requirement, then you can go for Interface.
Simple answer: Reuse and maintainability.
Suppose there are 4 concrete classes extending your abstract class which are all going to share some behaviors.
In this case it is better to implement the method in abstract class rather than defining it separately in all your concrete classes.
Concrete subclasses can use methods in the abstract superclass. So all shared functionality between subclasses can go into the base abstract class.
Code reusage. If you don't override non-abstract methods in your inheriting class(es) you inherit them from the abstract class.
To instead have them in the subclass violates the principle of DRY (don't repeat yourself): if all the subclasses have the same function, why write it repeatedly in every class?
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.