Java : Override not needed methods inside classes - Update [duplicate] - java

This question already has answers here:
Work around the need to override abstract methods in Java?
(2 answers)
Closed 7 years ago.
In my Project I have an abstract class that contains couple of abstract methods. Now multiple other classes extend that abstract class. Not all classes wants to override all the method of abstract class because that are not useful to them. How can I provide default implementation of those methods inside subclasses that aren't useful for the class?
Example-:
public abstract class Animal
{
public void Action()
{
.....
this.roar();
}
public abstract void roar();
public abstract void run();
}
Above is the abstract class that is going to have abstract methods that subclasses would implement.
public class Lion extends Animal
{
#Override
public void roar()
{
s.o.p("Lion roars");
}
#Override
public void run()
{
s.o.p("Lion runs");
}
}
public class Deer extends Animal
{
#Override
public void roar()
{
// Question : What should I do here?
}
#Override
public void run()
{
s.o.p("Deer runs");
}
}
EDIT-:
Thanks for suggestions, I understand the idea of having another class which can have method that aren't common ("roar" in this case).But My Project structure is a bit different and its kinda legacy code in which numerous subclasses extends from Animal class. Subclasses call a concrete method which in turn call abstract methods("roar" in this example, Please see updated Animal class with concrete method "Action").
Now as you suggested if I created another abstract class
public abstract RoaringAnimal extends Animal
{
public abstract void roar();
}
This will solve one of the problem as I can now just extent RoaringAnimal instead if Animal but other classes which calls Animal.Action method, they won't find implementation of roar() inside Animal and javac will complain.

If you have a method that is appropriate for a subclass but not for a superclass, like the roar method here, then you may want to provide another abstract class that subclasses Animal but provides roar, say, RoaringAnimal. The roar() method would no longer be declared in Animal, but in RoaringAnimal.
public abstract class RoaringAnimal extends Animal
{
public abstract void roar();
}
Then you can have Deer extend Animal, not implementing roar(), but you can have Lion extend RoaringAnimal, implementing roar().

Traditionally you do this:
#Override
public void roar()
{
throw throw new UnsupportedOperationException();
}
This exception was created for this purpose actually
#rgettman answer is more suitable though! try not to use this method ;) But know that it exists, You can find some examples in core Java libs

In such a case use an Adapter class. The adapter class will be a concrete class that extends your abstract class, but It will basically implements its methods with nothing or its methods implementation can throw an exception that extends RuntimeException.
There is a very nice example of this in Awt with the MouseAdapter class. See the javadoc here
Here is an example:
class AnimalAdapter extends Animal {
#Override
public void roar() {
throw new NotImplementedException();
}
#Override
public void run() {
}
}
A Sheep class for exemple will extend AnimalAdapter, but will get a RuntimeException only if it tries to call roar.
class Sheep extends AnimalAdapter {
#Override
public void run() {
System.out.println("I am a sheep I run, but I don't roar...");
}
}
Exemple of such an exception
class NotImplementedException extends RuntimeException {
}

One common solution are classes called Adapter classes. Those will implement all methods with a standard (or empty) implementation and you override the ones you want to change. The downside is, you don't know if the animal can do this or that.
Another possibility would be to split the abstract class into interfaces. Each set of methods that usually is combined together is put into one interface. The class will then implement the interfaces or not. This can end up in having feature interfaces for your animals (Roaring, Running, Crawling, ...), the animal implementation will then implement the interfaces it can fulfill. Dependencies between interfaces can be build by interface inheritance.
On Java8, there is the possibility to have default methods for interfaces, that could also be used for your classes. Instead of using the abstract baseclass, you use an interface with default methods.

Related

Inherit hidden methods

I have an interface that has 4 methods and a class that implements the interface. Here comes the question: "How can I inherit from the interface only 2 of those methods and my class don't became abstract?"
interface Class1 {
void method1();
void method2();
void method3();
void method4();
}
public class Class2 implements Class1 {
#Override
public void method1() {
}
#Override
public void method2() {
}
}
You have to get tricky, and you have to lookup why this works, especially if it's an interview question. It's basically for compatibility (the default methods in the interface), and requires Java 8.
public interface One {
void method1();
void method2();
void method3();
void method4();
}
public interface Two extends One{
default void method1(){}
default void method2(){}
}
public class Three implements Two{
#Override
public void method3() {}
#Override
public void method4() {}
}
Non-abstract Three.class implements method3 and method4 of One.class without defining method bodies for method1 and method2. Method1 and Method2 are defined with default implementations in interface Two.class.
You don't.
Somewhere in your inheritance chain those methods need to be implemented. That's the purpose of interfaces.
If you are using Java 8, there are new default implementations in interfaces, take a look at this page for details and that might help your case, barring that you need to have your concrete class inherit from an Abstract that provides an implementation for those 2 unwanted methods (even if its to print a cheerful "//TODO") message or remove them form the interface.
Firstly, you would get all the methods from the interface and wouldn't skip any. Then you have to implement the methods to satisfy interface contract. So it is better in your case to make 2 different interfaces and use them as you can implement multiple number of interfaces for a class.
interface ClassA {
void method1();
void method2();
}
interface ClassB {
void method3();
void method4();
}
An interface is used when you want a set of programs to follow a certain trend or acquire a common set of properties. These properties are declared as methods in the interface. An interface can have abstract methods only and it is compulosory to inherit these methods and define them some where down the inheritance line.
An abstract method would look like:
public void hello();
It has no method body. You need to inherit it and define the method body.
Let us consider an interface animal.
public interface animals
{
public void walks();
public void eats();
public void sleeps();
public void dog_breed();
public void barks();
}
Let us consider 2 classes named Jimmy_the_dog and Tom_the_cat.
We would want the these 2 classes to implement the interface animal to give it the properties of animals. But the problem is with the abstract methods barks() and dog_breed() in the interference. A dog can have all the properties mentioned in the interface animal but it does not make sense for a cat to inherit the methods barks() and dog_breed().
This is where we will split the interface. Here, we will split the animal interface to a dog interface and animal interface. Therefore, the properties in interface animal would become more common to animals in general.
public interface animals
{
public void walks();
public void eats();
public void sleeps();
}
public interface dog
{
public void barks();
public void dog_breed();
}
How to work around with the above two interfaces?
public class Tom_the_cat implements animal
public class Jimmy_the_dog implements animal implements dog
Jimmy_the_dog implements both the interfaces to acquire dog specific properties. Any animal which is a dog can do so. Similarly, you could make cat specific interfaces too for all the cats in the world.
The above interface could work in the following manner too:
public interface dog extends animal
public class Jimmy_the_dog implements dog
Jimmy_the_dog gets all the animal and dog properties.
Note:
A class can extend a single class only but it can implement multiple interfaces.
You can't do that. It comes down to what the implements keyword implies about a class.
An instantiable class cannot implement an interface without having all the methods of the interface implemented. If you don't implement all the required methods, you have to declare the class abstract or you have to remove the implements declaration.

What is the difference between using #override and not using it with interfaces?

this is my inteface.
public interface ConnectionListener{
public void onConnectionReady();
public void onConnectionDown();
}
I implement this interfaces in HomeActivity class.I would like to learn what is the differences between using #Override in implemented methods and not using #Override annotation...
public class HomeActivity implements ConnectionListener
{
#Override
public void onConnectionReady() {
}
#Override
public void onConnectionDown() {
}
}
#Override only shows the compiler that you would like to override a method. If the method signature is not known in a super class or an implemented interface you get a compile time error.
At runtime there is no difference.
For more Information see the javadoc.
If you have class B which extends class A (B extends A) can you use #Override to "replace" some method. You can modify how methods work in class B without replace it in class A. In overriden method you can invoked method from class A too by using "super" method and modify how it will work after super usage. In life you can use class Animal to extend class Dog and Cat. If Animal class had method getSound() you can for Dog override it for dog sound and for Cat for a cat sound. But Dog and Cat will have all artifacts which have animal like legs or other parts of body.
Interface you can use when you try to standardize some group class there will be same methods name but in interface you didn't implement a code of a method.
You can read more about it here:
Implements vs extends: When to use? What's the difference?
You will find the best usage of #Override tag when using it with static methods during inheritance.
Suppose class A has a static method EAT, class B extends class A and creates a static method EAT in class B. Now class A and B both have static method EAT with different implementation but it is not overridden, the moment you try to tag it with #Override, it shows you an error which means the sub-class has the same signature and different implementations but not overridden.

Should I implement all the methods present in an abstract class?

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

What do you do when a subclass can't implement an interface method because the superclass has a final method with the same signature?

Let's say you have a class that extends Activity and implements MyInterface, where Activity contains public final void setProgress(int progress) and MyInterface contains public abstract void setProgress(int progress)
I need to override the method from the interface, but I can't because Activty says it's final and can't be overridden.
What do I do?
Example:
public class MyActivity extends Activity implements MyInterface
{
#Override
protected void onCreate(Bundle bundle)
{
//stuff goes here
}
//Cannot override the final method from Activity
#Override
public void setProgress(int progress)
{
}
}
Let's also extend this question and say you don't have access to the source of MyInterface to change it, what does one do in such situations?
Use a decorator Design Pattern.
and here's a simplified example of the decorator pattern.
(adapted from the interwebs and polygenelubricants' answer on SO)
Note: before we begin remove the abstract keyword from the interface, that's wrong syntax
The class hierarchy is restructured as static inner classes so that the whole example is contained in one compilation unit (as seen on ideone.com):
Here's a diagrammatic overview of intended class hierarchy
public class AnimalDecorator {
static interface Animal {
public String makeNoise();
public void wagTail();
//other methods
}
static class Dog implements Animal {
public final String makeNoise() { return "woof"; }
public final void wagTail() { //do wag tail action }
}
static class DogDecorator implements Animal {
//delegate
private Animal animal;
public DogDecorator (Animal animal){this.animal = animal;}
public String makeNoise() { animal.makeNoise();}
public void wagTail() { animal.wagTail();}
}
static class LoudDog extends DogDecorator {
#Override public String makeNoise() {
return "WOOF WOOF WOOF!!!";
}
}
}
So here we have a simple Animal hierarchy, with Dog subclass. We also have a DogDecorator decorator -- also an Animal -- that simply delegates all methods to another Animal. That is, it doesn't really do any effective decoration, but it's ready to be subclassed so that actual decorations can be added.
We only have two methods here, makeNoise() and wagTail(). We then create the class we want LoudDog and use it. (Consider the case where Animal has many methods; then Normal would be most valuable).
Note that we can even stack one decoration on top of another. The exact implementation details may vary, but this simplified example pretty much captures the essence of the decorator pattern.
Steps
Subclass the original "Component" class into a "Decorator" class (see UML diagram);
In the Decorator class, add a Component pointer as a field;
Pass a Component to the Decorator constructor to initialize the Component pointer;
In the Decorator class, redirect all "Component" methods to the "Component" pointer; and
In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.
See also
Effective Java 2nd Edition, Item 18: Prefer interfaces to abstract classes
Related questions
Interface vs Abstract Class (general OO)
Is it just me or are interfaces overused?
You cannot override the final method because in the Java programming language, the final keyword is used to define an entity which cannot later be changed.
form Java Language Specification
Never tried but can give it a try.
You must implement the MyInterface in subclass too and can override the setProgress method of MyInterface and not of its superclass.
Should say..a good question:)
Edit:
In this case, the class cannot override the final method. So either your interface will have the exact same signature as the parent class (hence the interface is implemented automatically by inheritance), or you create a method with a different name.
The solution would largely depend on the circumstances, there's no textbook solution here.
Don't have your MyActivity implement MyInterface and instead create anonymous or inner class that implements it.
This ways you still have access to all MyActivity components and functions from setProgress(int) which is completly separate from final Activity.setProgress(int).

not implementing all of the methods of interface. is it possible?

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();
}
}

Categories