Is there any way to NOT implement all of the methods of an interface in an inheriting class?
The only way around this is to declare your class as abstract and leave it to a subclass to implement the missing methods. But ultimately, someone in the chain has to implement it to meet the interface contract. If you truly do not need a particular method, you can implement it and then either return or throw some variety of NotImplementedException, whichever is more appropriate in your case.
The Interface could also specify some methods as 'default' and provide the corresponding method implementation within the Interface definition (https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html). These 'default' methods need not be mentioned while implementing the Interface.
The point of an interface is to guarantee that an object will outwardly behave as the interface specifies that it will
If you don't implement all methods of your interface, than you destroy the entire purpose of an interface.
We can override all the interface methods in abstract parent class and in child class override those methods only which is required by that particular child class.
Interface
public interface MyInterface{
void method1();
void method2();
void method3();
}
Abstract Parent class
public abstract class Parent implements MyInterface{
#Override
public void method1(){
}
#Override
public void method2(){
}
#Override
public void method3(){
}
}
In your Child classes
public class Child1 extends Parent{
#Override
public void method1(){
}
}
public class Child2 extends Parent{
#Override
public void method2(){
}
}
I asked myself the same question, and then learned about Adapters. It solved my problem, maybe it can solve yours. This explains it very well : https://blogs.oracle.com/CoreJavaTechTips/entry/listeners_vs_adapters
You can do that in Java8. Java 8 introduces “Default Method” or (Defender methods) new feature, which allows a developer to add new methods to the Interfaces without breaking the existing implementation of these interfaces.
It provides flexibility to allow Interface define implementation which will use as default in the situation where a concrete Class fails to provide an implementation for that method.
interface OldInterface {
public void existingMethod();
default public void DefaultMethod() {
System.out.println("New default method" + " is added in interface");
}
}
//following class compiles successfully in JDK 8
public class ClassImpl implements OldInterface {
#Override
public void existingMethod() {
System.out.println("normal method");
}
public static void main(String[] args) {
ClassImpl obj = new ClassImpl ();
// print “New default method add in interface”
obj.DefaultMethod();
}
}
Define that class as an abstract class. However, you must implement those unimplemented methods when you want to create an instance of it (either by using a subclass or an anonymous class).
It is possible and it is easy. I coded an example.
All you have to do is inherit from a class that does implement the method. If you don't mind a class that is not instantiable, then you can also define an abstract class.
If you want an instantiable class, it is not possible. You may try to define an abstract class, though.
If you try to implement an interface and you find yourself in a situation where there is no need to implement all of them then, this is a code smell. It indicates a bad design and it violates Liskov substitution principle. Often this happens because of using fat interface.
Also sometimes this happens because you are trying to implement an interface from an external dependency. In this case, I always look inside the source code to see if there is any implementation of that interface which I can either use it directly or subclass it and override methods to my needs.
We can use Adapter classes ,which reduces complexcity by not making mandatory to implement all the methods present in the interface
Adapter class is a simple java class that implements an interface with only EMPTY implementation .
Instead of implementing interface if we extends Adapter class ,we provide implementation only for require method
ex--- instead of implementing Servlet(I) if we extends GenericServlet(AC) then we provide implementation for Service()method we are not require to provide implementation for remaining meyhod..
Generic class Acts as ADAPTER class for Servlet(I).
yes possible below shown is the way
interface Test {
void m() throws NullPointerException;
}
class Parent {
// Parent class doesn't implements Test interface
public void m() {
System.out.println("Inside Parent m()");
}
}
class Child extends Parent implements Test {
}
public class Program {
public static void main(String args[]) {
Child s = new Child();
s.m();
}
}
Related
I have an interface myIf, that i would like to have present at all levels of inheritance. The idea is that fooEverywhere needs to be at GrandParent and Parent and further children. So this obvious pattern occurs:
public interface myIf {
void fooEverywhere ();
}
public class GrandParent implements myIf {
#Override
public void fooEverywhere() { /* Actions */ }
}
public class Parent extends GrandParent implements myIf {
#Override
public void fooEverywhere() { super.fooEverywhere(); /* And Other actions */ }
}
However, if i forget / miss Parent like this:
public class Parent extends GrandParent /*implements myIf*/ {
// #Override
// public void fooEverywhere() { super.fooEverywhere(); /* And Other actions */ }
}
Java, will still be OK, as parentObject.fooEverywhere() will find GrandParent.fooEverywhere().
Therefore how can i redesign this to force Java to recognise that fooEverywhere must be in Parent ?
The short answer is that you can't.
The longer answer is that you can't because you've already provided an implementation in a class higher in the inheritance chain. Once it's implemented higher in the chain, it's implemented.
You could create an abstract class as the ancestor which implements the interface and then declare the interface methods as abstract on the abstract ancestor. Then both GrandParent and Parent would then extend AbstractParent and have to provide their own implementations of the interface methods that were declared as abstract.
Note, interfaces in Java are typically Pascal-case, i.e. MyIf, not myIf. Also, there is no need to actually use the implements keyword in a descendent class that has a parent already declaring it implements an interface.
As you already said, the compiler does not care as long as as a superclass provides an implementation of the abstract or interface method.
I can hardly imagine any usecase where it it necessary to implement a method in every subclass, but if you really need it you can implement a solution using reflection with Class#getDeclaredMethods (only return the methods declared in this class) to validate if each of the classes implements or overrides the method. If not, throw an exception.
Is abstraction possible without inheritance? This is my code
abstract class whatever
{
abstract void disp1();
abstract void disp2();
abstract void disp3();
}
class what {
void disp1()
{
System.out.println("This is disp1");
}
}
public class threeClasses {
public static void main (String args[])
{
what obj =new what();
obj.disp1();
}
}
Please note above, how i:
did not extend the class "what" from abstract class "whatever" and yet the code runs perfectly with no errors
Did not declare class "what" as abstract (since it's not declaring the other two methods disp2() and disp3())
I am very confused. Please help.
You aren't using whatever (and Java naming conventions should be respected). The idea behind an abstract class (and inheritance) is that there is an interface contract. Let's examine it with a more practical example,
abstract class Whatever {
abstract void disp1();
void disp2() {
System.out.println("disp2");
}
void disp3() {
System.out.println("disp3");
}
}
Then make What extend it. Override two methods for demonstration (the annotation is a useful compile time safety check)
class What extends Whatever {
#Override
void disp1() {
System.out.println("This is disp1");
}
#Override
void disp2() {
System.out.println("This is disp2");
}
}
Finally, invoke methods on a What instance through the Whatever contract
public static void main(String args[]) {
Whatever obj = new What();
obj.disp1();
obj.disp2();
obj.disp3();
}
Which outputs
This is disp1
This is disp2
disp3
Note that What is providing the implementation for disp1 and disp2 while Whatever provides disp3.
There is no relationship between your abstract class and your concrete class. Whatever your definition of "abstraction", it actually represents a relationship between types. The abstract keyword does not establish that relationship between classes, it represents that relationship, and not by itself. The relationship needs to be extended from both sides.
abstract is a declaration from one side about a promise that must be kept, for an inheriting type either to implement abstract methods or to ask for that promise from its inheriting types.
The other side makes the promise by being a class that inherits from the abstract type. Without inheritance, the concrete type loses the is-a connection.
You will get the compiler error you're complaining about missing if you correct one major mistake you made. You failed to use the #Override annotation. Always use the #Override annotation when you intend to override a method, or you will forever enjoy just the sort of bug you show here.
I think what he meant was if we can implement abstract class's method without inheriting abstract class.
You might be thinking if we can do it with composition/association/aggregation relation.
To that, I will answer: NO because you can't create an object of abstract class as in these relations you have to make object or reference of the object.
So, the only way to implement abstract methods is through inheritance.
This is a logical development of another question I asked.
Supposedly you have an interface, some methods of which might either be supported by a concrete implementation or not. The goal is to provide a reasonable way for the client to find out whether his particular implementation supports each particular method and to recover if it doesn't.
The solution I came up with utilizes the standard java.lang.UnsupportedOperationException, which is thrown by the concrete implementation if the method is unsupported:
public interface CommonInterface {
void possiblyUnsupportedOperation () throws java.lang.UnsupportedOperationException;
}
However, this is claimed to be a bad solution, since the exception mechanism should not be used as a means of checking whether an operation is available. So the alternative suggestion is to use tester methods:
public interface CommonInterface {
void possiblyUnsupportedOperation ();
boolean isOperationSupported ();
}
But what if the interface has a whole multitude of optional operations? Should I use multiple tester functions? Should I create a separate Enum to map the optional methods onto and pass it as a method descriptor to a single tester function? Both variants look kinda clunky to me.
Is there an alternative way that is both an elegant code and a good design solution?
If you own that interface you could extract a Parent interface with the methods that are always going to be implemented and inherit from that interface.
public interface ParentCommonInterface {
void method1();
void method2();
}
public interface CommonInterface extends ParentCommonInterface {
void possiblyUnsupportedOperation();
}
class MyClass implements ParentCommonInterface {...}
If you don't own that interface you can create an Adapter class and use that one to declare the object.
public interface CommonInterface {
void possiblyUnsupportedOperation();
boolean isOperationSupported();
}
public class AdapterClassOne implements CommonInterface {
void possiblyUnsupportedOperation() {...}
boolean isOperationSupported() {return false;}
}
}
interface TestInterface {
void work();
}
class TestClass {
public void work(){
System.out.println("Work in CLASS");
}
}
public class Driver extends TestClass implements TestInterface {
public static void main(String[] args) {
new TestClass().work();
}
}
Can any one explain to me, why just because the same work method signature exists in TestClass this class compiles fine?
The requirement of implementing an interface is that the class provides implementations of all the methods specified by the interface. Class Driver provides the required implementation of work(), because it inherits an exactly matching method from TestClass. So it can be used as an implementation of TestInterface.
It's because all of interface's methods are implemented.
It's the same reason you can omit #Override annotation in your implementation class (not a good practice as a method signature could be changed and you can come into position where you are unintentionally implementing changed method with some other of your public methods).
However, your construct is shaky because you are depending on TestClass which is not aware of the interface you're signing to implement
Below is the code snippet:
public abstract class MyAbstractClass {
public abstract void a();
public abstract void b();
}
public class Foo extends MyAbstractClass {
public void a() {
System.out.println("hello");
}
public void b(){
System.out.println("bye");
}
}
public class Bar extends MyAbstractClass {
public void a() {
System.out.println("hello");
}
public void delta() {
System.out.println("gamma");
}
}
There are couple of questions that I have:
Q-1 :- Should I implement ALL the methods in abstract class?
Q-2 :- Can the implementing class have its own methods?
When you extend an Interface or an Abstract class you are creating a contract of sorts with that superclass. In the contract you are saying:
"I will implement all unimplemented methods in my superclass"
If you do not, implement all the unimplemented methods, then you are breaking your contract. A way to not break your contract is make your subclass Abstract as well as a way of saying
"I have not implemented all the classes in my contract, I am going to
have my subclasses implement them".
For your class bar right now, you must implement b() or make bar an Abstract class or you are not fulfilling your contract with MyAbstractClass
The basic idea is:
Interface: None of my methods are implemented. A subclass must implement all my methods in order to implement me. (Note: I believe default interfaces have been added to Java 8 which may change this a bit)
Example:
public interface myInterface
{
//My subclasses must implement this to fulfill their contract with me
public void methodA();
//My subclasses must implement this to fulfill their contract with me
public void methodB();
}
Abstract: I may implement some of my methods, but I will also leave methods as abstract so that my subclasses must implement because they can implement those classes to suit their needs better than I can.
Example:
public abstract class myAbstractClass
{
//My subclasses must implement this to fulfill their contract with me
public abstract void methodC();
public void helloWorld()
{
System.out.println("Hello World");
}
}
Abstract classes can also extend interfaces so they can implement some of their methods. But they can also leave some of the methods unimplemented so the subclass can implement them. If you leave an interface method unimplemented, there is not need to declare it abstract, it is already in the contract.
Example:
public abstract class myAbstractClass2 implement myInterface
{
#Override
public void methodA()
{
// this fulfills part of the contract with myInterface.
// my subclasses will not need to implement this unless they want to override
// my implementation.
}
//My subclasses must implement this to fulfill their contract with me
public abstract void methodD();
}
So in essence, an abstract class doesn't have as strict a contract with it's superclass because it can delegate its methods to its subclasses.
Regular Class: (I use regular to mean non-interface, and non-abstract). I must implement all unimplemented methods from all of my superclasses. These classes have a binding contract.
Example:
public class mySubClass extends myAbstractClass2
{
#Override
public void methodB()
{
//must be implemented to fulfill contract with myInterface
}
#Override
public void methodD()
{
//must be implemented to fulfill contract with myAbstractClass2
}
public void myMethod()
{
//This is a method specifically for mySubClass.
}
}
Q-1:- Should I implement all methods in abstract class?
Yes, you must implement all abstract methods.
Q-2 :- Can the implementing class have its own methods?
Yes, you can declare own (more specfic) methods.
You not only should, but have to implement all abstract methods (if the subclass is non-abstract). Otherwise an object of that subclass wouldn't know what to do if that method was called!
The only way to prevent this is if the subclass is also declared abstract, so that it cannot be instantiated in the first place.
You don't have to implement all methods of an abstract class. But you must implement all abstract methods of it.
In fact extending an abstract class has no difference then extending a normal class. It's not like implementing interfaces. Since you're extending you are creating a subclass thus you can add as many methods and attributes as you need.
Ya definately implementing class can define its own method as well and if are not implementing all the methods of your abstract class in the derived class then mark this derived class also as Abstract
but at the end of chain you have to make one concrete class which implements all the method that was not implement in abstract sub-parent
public interface I{
public void m();
}
public abstract class A1 implements I{
//No need to implement m() here - since this is abstract
}
public class B1 extends A1{
public void m(){
//This is required, since A1 did not implement m().
}
}
public abstract class A11 extends A1{
//Again No need to implement m() here - since this is abstract
public abstract void newA11Method()
}
public class B11 extends A11{
//This class needs to implement m() and newA11Method()
}
Yes, the implementing class need only implement the methods labeled as abstract in the abstract class.
Yes you must implement all the methods present in an abstract class. As the purpose of abstract class is purely to create a template for the functions whose implementation is decided by the class implementing them. So if you don't implement them, then you are breaking the concept of abstract class.
To answer your second question, yes you can create any number of your own methods irrespective of the abstract class you are extending.
Yes, When you are implementing an Interface you will have to implement all its methods. That is the purpose of defining an Interface. And yes, you can have your own methods in the class where you implement an Interface.
Yes, when you extends abstract you should give implementation for all abstract methods which are presents in abstract class. Othrewise you should make it implementation class as abtract class.
You must implement all the abstract methods you have in the abstract class. But you can directly use the concrete methods that are implemented.
For more information please refer to the :
https://www.javatpoint.com/abstract-class-in-java