Inherit hidden methods - java

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.

Related

Abstract method implementation (if unused)

For instance, I have an abstract class implemented like this:
public abstract class Animal
{
public abstract void makeNoise();
}
and I have a child class which is representing an animal that does not make any noise. Which is better?
public class Turtle extends Animal
{
// properties and methods
public void makeNoise()
{
//leave it empty
}
}
or should i simply make it : public abstract void makeNoise(); inside Turtle?
It is better to move the makeNoise() method out of Animal as all the animals doesnot make noise. So create another interface NoiseMaker and add the the makeNoise method inside that.
public abstract class Animal {
// animals methods
}
public interface NoiseMaker {
void makeNoise();
}
public class Turtle extends Animal {
// properties and methods which are applicable for turtle
}
And when you want an animal which makes noise like Lion you can extend Animal class and implement NoiseMaker, so that it has the behaviour of Animal as well as it makes noise.
public class Lion extends Animal implements NoiseMaker {
public void makeNoise() {
// implementation
}
// other properties and methods which are applicable for turtle
}
What people often do: throw some sort of exception, like UnsupportedOperationException or something alike.
But: in the end your are fixing a symptom here.
The point is: extending a base class means that an object of the derived class IS-A object of the base class as well. And you are asking: how to violate the public contract of the base class.
And the answer is: you should not do that. Plain and simple.
Because if you start throwing exceptions here, all of a sudden, a caller that maybe has List<Animal> animals can't simply invoke makeNoise() on each object. The caller has instead to use instanceof (so that he can avoid calling makeNoise() on specific classes) - or try/catch is required.
So the real answer is: step back and improve your model. Make sure that all methods on the base class make sense for derived classes. If not - maybe introduce another layer, like abstract class NoisyAnimal extends Animal.
This is the best use case to use UnsupportedOperationException
You have to implement because of the abstract design. So just implement the method and throw UnsupportedOperationException exception.
Keep it Animal, cause most of the Animal's make sound :) If you move it to Turtle, all the subclasses again have to have their own voice method.
or should i simply make it : public abstract void makeNoise(); inside Turtle?
If you do, Turtle is abstract. So the question isn't which is better, the question is, do you want to be able to instantiate Turtle or not?
If you do, you have to implement the method.
If you are okay with it being abstract, then declare it abstract and don't list the method at all:
public abstract class Turtle extends Animal {
}
You might want to distinguish between Animals making noises or not. Something a long the lines of
public abstract class Animals {}
public abstract class AnimalsNoisy extends Animals { abstract void makeNoise(); }
You would then use Turtle extends Animals. The advantage of this structure is if you have a List of Animals you don't need to worry if they implemented the makeNoise method or not e.g.
for(AnimalsNoisy animal: ListAnimalsNoisy) { animal.makeNoise();}
It is a good example to learn how to make your code loosely coupled.
By loosely coupled I mean, if you decide to change or modify your code you will not touch your previous code. Sometimes it is referred as OPEN-CLOSE principle.
For this first you have to identify what part of your code is frequently changing.
Here the method makingNoise() will have different implementation based on your class.
This design can be achieved in following steps.
1) Make an interface which will have implementation for makeNoise()
method.
public interface NoiseInterface {
public void speak();
}
2) Create concrete implementation for NoiseInterface
eg: For Fox
public class FoxSound implements NoiseInterface {
#Override
public void speak()
{
//What does the fox say ?
Sysout("chin chin chin tin tin tin");
}
}
3: Provide the Noise Interface in Animal Class
public abstract class Animal
{
public NoiseInterface noiseMaker;
public abstract void makeNoise();
}
4: Just provide the Type of NoiseInterface of your choice in Fox Class
public class Fox extends Animal
{
public Fox()
{
noiseMaker = new FoxSound();
}
public void makeNoise()
{
noiseMaker.speak();
}
}
Now Amazing thing about this design is you will never have to worry about the implemetation. I will explain you how.
You will just call
Animal me = new Fox();
fox.makeNoise();
Now in future you want to mute the Fox.
You will create a new Interface Mute
public class Mute implements NoiseInterface {
#Override
public void speak()
{
Sysout("No sound");
}
}
Just change the NoiseBehavior in Fox class constructor
noiseMaker = new Mute();
You can find more on OPEN-CLOSE Principle Here
You may write like this,is this what you want?
public interface NoiseInterface {
void makingNoise();
void makingNoNoise();
}
public class Animal implements NoiseInterface{
#Override
public void makingNoise() {
System.out.println("noising");
}
#Override
public void makingNoNoise() {
System.out.println("slient");
}
}
public class Turtle extends Animal{
#Override
public void makingNoNoise() {
System.out.println("turtle");
super.makingNoNoise();
}
}

Interface extending a class

Let's say that I have an interface, and all classes that implement that interface also extend a certain super class.
public class SuperClass {
public void someMethod() {...}
}
public interface MyInterface {
void someOtherMethod();
}
//many (but not all) sub classes do this
public class SubClass extends SuperClass implements MyInterface {
#Override
public void someOtherMethod() {...}
}
Then if I'm dealing with an object of type MyInterface and I don't know the specific sub class, I have to hold two references to the same object:
MyInterface someObject = ...;
SuperClass someObjectCopy = (SuperClass) someObject; //will never throw ClassCastException
someObjectCopy.someMethod();
someObject.someOtherMethod();
I tried making the interface extend the super class, but it's a compiler error:
public interface MyInterface extends SuperClass {} //compiler error
I also thought of combining the interface and the super class into an abstract class like so:
public abstract class NewSuperClass {
public void someMethod();
public abstract void someOtherMethod();
}
But then i can't have a sub class that doesn't want to implement someOtherMethod().
So is there a way to signify that every class that implements an interface also extends a certain class, or do I have no choice but to carry around two references to the same object?
I think that the only solution you have would be to have a reference to both, but this indicates that you have a design flaw somewhere. The reason I say is because you should think of an interface as something that your implementing classes will always need. For example, a Car and Airplane both need a Drive() interface. A design reconsideration is probably worth your time. However, if you still want to follow that path, you can do the following:
public class ClassA {
public void methodA(){};
}
public abstract class ClassB extends Class A{
public void methodB();
}
After you have the above setup, you can now reference an object that has the two methods by doing the following:
ClassB classB = new ClassB();
classB.methodA();
classB.methodB();
Now you don't actually have to actually use two pointers to the same object.

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

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.

How does an abstract method differ when it is defined in an abstract class or an interface?

Assume an abstract class has only abstract methods declared in it and the interface has abstract methods.
How does this affect the abstract method m?
abstract class A {
abstract void m();
}
interface A {
abstract void m();
}
Even if the abstract class is a pure abstract, i.e. contains only abstract methods and does not contain state, your subclass extends this class and therefore you have single inheritance only.
However you can implement several interfaces.
Therefore if you want to force your classes to be a subclass of your A and not to be subclass of something else, use abstract class. Otherwise define interface.
Interfaces are also more useful when you don't exactly know if all your entities will need to override a specific method. Consider for instance birds, some can fly and some can't. You don't want to force overriding a fly() method in all Bird subclasses.
public abstract class Bird(){
...
public abstract void eat(); //all birds eat
public abstract void sleep(); //all birds sleep
public abstract void fly(); //is wrong here since not all birds can fly
}
A more correct way would be to define interfaces for specific cases, so in this case
public interface Flyable{
abstract void fly();
}
Then you can define your subclasses as birds that can fly or not based on the fact they implement the Flyable interface or not.
public class Eagle extends Bird implements Flyable{
#override
public void fly(); //needed
-----
}
public class Ostrich extends Bird{
//does't fly
}

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

Categories