restriction of method while implementing an interface - java

I have two methods in an interface:
public interface MyInterface {
public void methodOne();
public void methodTwo();
}
public class MyClass implements MyInterface{
public void methodOne(){
//implementation code
}
public void methodTwo(){
//implementation code
}
}
Can I restrict one of them while implementing the interface?

You must implement all methods of your interface, unless the class implementing the interface is abstract.
If by restrict you mean that you want to predefine one or more of the methods, then you can use an abstract class instead of the interface. Abstract methods in an abstract class are methods that must be implemented by any class that extends the abstract class. Non-abstract methods are actually implemented in the abstract class, itself.
For example,
public abstract class MyClass
{
abstract void methodOne();
void methodTwo()
{
//implementation code
}
}
public class MyOtherClass extends MyClass
{
void methodOne()
{
//implementation code
}
}
Here's a reference for Abstract Classes and Methods.
EDIT 1 (in response to comment):
I'm not really sure what you mean by a burden. All I'm saying is that if you want all methods to be implemented by the class, then use an interface.
If you only want some of the methods implemented by a class, then you can either use an abstract class instead of the interface
or
If it makes sense, have an abstract class implement the interface (partially) and then have the remainder of the methods implemented by whatever extends the abstract class.
Both approaches are reasonable. It depends on what you really need to do.
EDIT 2 (in response to additional comments):
Providing one user class with additional features seems like the perfect application for just extending the "normal user class" with a "super user" class that has the additional features. If you need an interface for the "super user" class, you can create an interface that extends the interface implemented by the "normal user" class.

No you have to implement all methods if your class implements an interface.
Unless it is abstract.
Check this discussion for more details.

You can use an abstract class; they do not need to implement all the entire interface. However, they cannot be instantiated. You must implement all methods in order to instantiate an implementation of an interface.

Except the abstract class, you are bound to implements all methods of interface.

You can not put restriction on Interface, but YES you can achieve In Abstract class and NO in concrete class.

Couple of solutions :
Either mark the class as abstract. But in that case you cannot instantiate your implementing class.
Simply add black implementation in your class.

Not sure what you mean by "restrict". You have to implement the method. However, you could simply do
public void method1(someargs) {
throw new UnsupportedOperationException();
}
as is done by many Collection implementations.

Related

Do Abstract classes need to implement an entire interface in java 7?

I need a group of different classes to implement a certain interface. However, a lot of those classes, but not all of them, need a same implementation for some of the methodes defined in the interface. I was wondering if I could make an abstract class implement the interface and only create the methods that are the same for those classes?
For example, I have interface A:
public interface A{
public returnType method1(){};
public returnType method2(){};
}
Can I do this:
public abstract class AbstractPartialA implements A{
#Override
public returnType method1(){
implementation
}
}
and than have the classes extending from this Abstract class implement the remaining methods that are required to fulfill the interface?
Yes, you can, that is the exact purpose of abstract classes.
Do Abstract classes need to implement an entire interface in java 7?
And the answer is " NO ". Abstract class can implement entire interface or it can implement only some methods of an interface.
Case-1
If it implements entire interface and is still declared as 'abstract', it means we don't want other(people who are going to use our class) to create object for our class
Example of such class is HttpServlet in javax.servlet.http . Here HttpServlet class doesn't have any abstract method, but still it is declared as 'abstract'
Case-2
Simple, if the class doesn't implement any one of the method of an interface, then it is declared as 'abstract'. Now it will be the responsibility of the other class which extends the abstract class to provide the implementation of such method which is not implemented by 'abstract class'
You can, and when you try to extend from AbstractPartialA Java will ask you to:
Implement all methods declared in implemented interfaces and not implemented
Implement all methods declared as abstract in superclasses
Remember that a class is considered to implement all interfaces implemented by its superclasses, not just the ones specifically written after the implements keyword in this class' declaration. This applies both to the types of the class (and thus the types of its references) and to the methods it is required to implement.

Why doesn't interfaces implement methods and override them?

I already read the post of research effort required to post a SO question. I am ashamed again to post this question to a pile of million questions. But I still don't get the idea of interfaces in java. They have unimplemented methods and then defined for every class in which they are implemented. I searched about it. Interfaces were used to support multiple inheritance in java and also to avoid (Deadly) Diamond Death of inheritance. I also came across Composition vs Inheritance and that inheritance is not for code reuse and its for polymorphism. So when I have a common code as a class to extend it will not be supported due to multiple inheritance which gives the option to use Interfaces(Correct me if I am wrong). I also came across that its not possible in most cases to define a generic implementation. So what is the problem in having a common definition (not a perfect generic implementation) of the interface method and then Override it wherever necessary and why doesn't java support it. Eg. When I have 100 classes that implements an interface 70 of them have a common implementation while others have different implementation. Why do I have to define the common method in interface over 70 classes and why can't I define them in Interface and then override them in other 30 classes which saves me from using same code in 70 classes. Is my understanding of interfaces wrong?
First, an interface in Java (as of Java 7) has no code. It's a mere definition, a contract a class must fulfill.
So what is the problem in having a common definition (not a perfect
generic implementation) of the interface method and then Override it
wherever necessary and why doesn't java support it
Yes you can do that in Java, just not with interfaces only. Let's suppose I want from this Example interface to have a default implementation for method1 but leave method2 unimplemented:
interface Example {
public void method1();
public String method2(final int parameter);
}
abstract class AbstractExampleImpl implements Example {
#Override
public void method1() {
// Implement
}
}
Now classes that want to use this method1 default implementation can just extend AbstractExampleImpl. This is more flexible than implementing code in the interface because if you do so, then all classes are bound to that implementation which you might not want. This is the advantage of interfaces: being able to reference a certain behavior (contract) without having to know how the class actually implements this, for example:
List<String> aList = MyListFactory.getNewList();
MyListFactory.getNewList() can return any object implementing List, our code manipulating aList doesn't care at all because it's based on the interface.
What if the class that uses interface already is a Sub-class. Then we
can't use Abstract class as multiple inheritance is not supported
I guess you mean this situation:
class AnotherClass extends AnotherBaseClass
and you want to extend AbstractExampleImpl as well. Yes, in this case, it's not possible to make AnotherClass extend AbstractExampleImpl, but you can write a wrapped inner-class that does this, for example:
class AnotherClass extends AnotherBaseClass implements Example {
private class InnerExampleImpl extends AbstractExampleImpl {
// Here you have AbstractExampleImpl's implementation of method1
}
}
Then you can just internally make all Example methods being actually implemented by InnerExampleImpl by calling its methods.
Is it necessary to have the interface in AnotherClass?
I guess you mean AnotherClass implements Example. Well, this is what you wanted: have AnotherClass implement Example with some default implementation as well as extend another class, or I understood you wrong. Since you cannot extend more than one class, you have to implement the interface so you can do
final Example anotherClass = new AnotherClass();
Otherwise this will not be possible.
Also for every class that implements an interface do I have to design
an inner class?
No, it doesn't have to be an inner class, that was just an example. If you want multiple other classes have this default Example implementation, you can just write a separate class and wrap it inside all the classes you want.
class DefaultExampleImpl implements Example {
// Implements the methods
}
class YourClass extends YetAnotherClass implements Example {
private Example example = new DefaultClassImpl();
#Override
public void method1() {
this.example.method1();
}
#Override
public String method2(final int parameter) {
return this.example.method2(parameter);
}
}
You can create an abstract class to implement that interface, and make your those classes inherit that abstract class, that should be what you want.
A non abstract class that implements and interface needs to implement all the methods from the interface. A abstract class doesn't have to implement all the methods but cannot initiated. If you create abstract class in your example that implements all the interface methods except one. The classes that extend from these abstract class just have to implement the one not already implemented method.
The Java interfaces could have been called contracts instead to better convey their intent. The declarer promise to provide some functionality, and the using code is guaranteed that the object provides that functionality.
This is a powerful concept and is decoupled from how that functionality is provided where Java is a bit limited and you are not the first to notice that. I have personally found that it is hard to provide "perfect" implementations which just need a subclass or two to be usable in a given situation. Swing uses adapters to provide empty implementations which can then be overrides as needed and that may be the technique you are looking for.
The idea of the interface is to create a series of methods that are abstract enough to be used by different classes that implement them. The concept is based on the DRY principle (Don't repeat yourself) the interface allows you to have methods like run() that are abstract enough to be usuable for a game loop, a players ability to run,
You should understand the funda of interface first. Which is
It is use to provide tight coupling means tight encapsulation
It helps us to hide our code from the external environment i.e. from other class
Interface should have only definition and data which is constant
It provide facility to class open for extension. Hence it cannot be replace by the any other class in java otherwise that class will become close for extension. which means class will not be able to extend any other class.
I think you are struggling with the concept of Object Oriented Design more than anything. In your example above where you state you have 100 classes and 70 of them have the same method implementation (which I would be stunned by). So given an interface like this:
public interface Printable
{
void print();
}
and two classes that have the "same" implementation of print
public class First implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
public class Second implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
you would instead want to do this:
public abstract class DefaultPrinter implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
now for First and Second
public class First extends DefaultPrinter
{
}
public class Second extends DefaultPrinter
{
}
Now both of these are still Printable . Now this is where it gets very important to understand how to properly design object hierarchies. If something IS NOT a DefaultPrinter YOU CANNOT AND SHOULD NOT make the new class extend DefaultPrinter

Require override of specific methods of a non-abstract class

Is it possible to have a class defined like
public class MyClass
{
public void methodA(){} // Inherit
public void methodB(){} // Inherit
public void methodC(){} // Require override
}
and then have all classes which extend from MyClass to be required to override methodC() but just simply inherit methodA() and methodB()?
If it is possible, how does one do it? If it's not possible, can you propose an alternative solution to achieve a similar result?
EDIT:
I need a non-abstract class because I want to be able to instantiate this class too.
You would have to make your base class abstract.
public abstract class MyClass
{
public void methodA(){} // Inherit
public void methodB(){} // Inherit
public abstract void methodC(); // Require override
}
You cannot require an override of a non-abstract method.
Maybe you can do something similar to the template method pattern:
public final void methodC() { methodC1(); someMoreLogic(); methodC2();}
protected abstract void methodC1();
protected abstract void methodC2();
Here methodC encapsulates a fixed algorithm that calls into pieces that have to be supplied by the subclasses.
I don't think you do exactly what you want. Alternatively, create MyBaseClass as an abstract class with methodC() abstract implementations for methodA() and methodB(). Derive MyClass from it, adding an implementation for methodC(). Any classes that you do not want to have inherit that implementation should directly subclass MyBaseClass rather than MyClass.
If you want a method to be just inherited use final keyword. To force overriding make it abstract. However, only non-abstract child classes will have to override it.
AFAIK there is no way to force override a method in Java with out abstract.
You can achive with abstract class by making the method as abstract method.
one way to do it may be to use virtual keyword instead of abstract but it doesnt require to override, but you can do override. though so, you can instantiate.
another way and more recommended is to create an interface where you can indicate what the class requirements. it is something like abstract, you indicate what to require, but keep in mind interface is not a class. it's more like pointer. for more for interface click: https://docs.oracle.com/javase/tutorial/java/concepts/interface.html
So, java.lang.Thread is a concrete class that implements the Runnable interface. Therefore, it must be that Thread implements a public void run() method. Yet, when you extend Thread, like MyClass extends Thread { }, you are required to implement the run() method.
It stands to reason that there is a way to force overriding of a method without making the containing class abstract.

From where Function will be inherit and why?

Suppose we have one class implements Interface extends abstract class with same abstract function in both Interface and abstract class. Then class inherit which function Interface or abstract class and why.
Like:
public class A extends B implements I
{
public void set()
{
// Some code here
}
}
Interface:
public interface I {
public void set();
}
abstract Class:
public abstract class B
{
public abstract void set();
}
Both. As long as the functions signatures match, the compiler will accept this "double"-inheritance. Keep in mind implementing interface's methods is only a "contract" your class has to verify to be compilable. Implementing the interface only means "my concrete class has to have a method set()". Extending the abstract class B means "my concrete class inherits the method set() from its superclass, and as it's defined as abstract, it needs to implement it". When both these propositions match (as per your example), all is fine.
If there is a difference in the signature of the functions between the interface and the abstract class, your concrete class must then implement both versions.
BTW, slightly off-topic, try to avoid abstract classes as much as you could. If an abstract class has only abstract methods, then it should be an interface. If it has some code in some of its method, then you should probably think about refactoring it to use composition rather than inheritance. Inheritance is evil ;)
It doesn't matter to know from which the method will be inherited because the method in both Interface and Abstract class are abstract meaning no implementation is given.
So all you have to ensure in your concrete class that you must implement all the method defined in the interface but not implemented in the abstract class . AND implement all the abstract methods defined in its superclasses (even if they are not defined in an interface) (from Guillaume)

I've found many questions on abstract classes and interfaces but answer me this: Can an abstract class do everything an interface can?

I'm really confused, and I've read a TON of questions on this topic and I have not been able to pinpoint anything specifically that an interface can do that an abstract class cannot do.
Is there anything an interface can do that an abstract class cannot do?
I am asking in the context of my Java class, but feel free to remove the java tag if it applies to other languages as well (possibly C#?).
Edit: I understand that an abstract class can do things an interface cannot, but if an abstract class can do everything an interface can do, then what is the point of an interface? What does "implement multiple interfaces" mean?
Interfaces as such cannot do what abstract classes do.
This is because abstract classes can contain code - interfaces cannot. But any given class can only have one superclass - extends - as opposed to any number of interfaces - implements, so if you use abstract classes you essentially paint yourself in a corner of the inheritance tree, because your class can only extend a single class.
This limitation does not apply to interfaces, allowing a single class to have many purposes depending on how many interfaces it implements.
You can't inherit from multiple abstract classes in c#, but you can implement multiple interfaces.
I think this may apply to java too
Edit:
You can't inherit from multiple classes. If you have an abstract class called Clonable, and an abstract class called Disposable then you can only inherit one of these classes and you're forced to make a decision about which class your class should be a subtype of:
e.g:
public abstract class Clonable
{
public abstract void Clone();
}
public abstract class Disposable
{
public abstract void Dispose();
}
// MyClass cannot be Disposable too, it is not allowed by the language
public class MyClass : Clonable
{
override void Clone()
{
}
}
Note it is a design decision of the language to allow you only to inherit from one class.
If on the other hand you have interfaces, the language allows you to implement both
e.g.
public interface IClonable
{
void Clone();
}
public interface IDisposable
{
void Dispose();
}
public class MyClass : IClonable, IDisposable
{
void IClonable.Clone()
{
}
void IDisposable.Dispose()
{
}
}
Well read:
http://mindprod.com/jgloss/interface.html
http://mindprod.com/jgloss/interfacevsabstract.html
What does "implement multiple interfaces" mean?
Consider:
public static interface Ifun extends Comparable<Ifun>, Serializable {}//or
public static class Cfun2 implements Comparable<Cfun>, Serializable
When class implements Ifun, then:
Comparable interface imposes a total ordering on the objects of each class that implements it. Objects that implement this interface can be sorted automatically by Collections.sort.
The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
It means object can have more then 1 interface.
Interfaces are non instantiable classes that only contains methods that subclasses can inherit. The only thing that interfaces can do (in java) is that a class can implement many interfaces while a class can only extend 1 abstract class.

Categories