Usings abstract class to add a method to an interface - java

I want to add a method to an interface, but i do not want to rewrite all the implementations (i only need to use it in one or two implementation). I read that i can achive this with the use abstract classes, but i cant quite figure out how its done?
Inteface:
public interface Animal {
public void doSound();
}
Classes:
public class Cat implements Animal {
#Override
public void doSound() {
System.out.print("meow");
}
}
public class Dog implements Animal{
#Override
public void doSound() {
System.out.print("bark");
}
}
What i want is to be able to call
animal.doSomethingElse()
but i dont want to add this method to every implementation. Can this be done?
EDIT:
Should have mentioned this before, i am not using java 8.

You could change Animal into an abstract class. This will enable you to selectively implement methods:
public abstract class Animal {
public abstract void doSound();
public void doSomethingElse() {
}
}

It is possible in Java 8 with help of default method in interface.
public interface Animal {
void doSound();
default void doSomethingElse(){
// do something
}
}
In case of default methods, your implemented classes from Animal doesn't have to override them.
prior to java 8, you have to make your Animal class abstract and add method implementation there.

It is not possible with Java including versions to 7.
You can define interface Animal as abstract class and implement new method within it. Sample code as follows:
public abstract class Animal {
public abstract void doSound();
public void doSomethingElse() {}
}
However if you are using Java 8 you have mechanism which is called default methods. Example below
public interface Sample {
public abstract void doSound();
public default void doSomethingElse() {};
}
default methods do not have to be implemented by classes. Mechanism is very useful when it comes to interfaces with large number of classes implementing certain interface. You can extend it without changing all classes

Unfortunately, no: you cannot add a method to an interface without having to recompile all implementations of the interface.
You can add a method to the abstract class, and change all references to the interface with references to your abstract class. That, however, defeats the purpose of having the interface in the first place.
Finally, in Java 8 you can address this problem by providing a default implementation of a method in an interface. If Java 8 is an option, I would definitely recommend this route.
If you would like to avoid problems like this in the future, you could follow the interface + adapter pattern that Java designers have been following in the AWT framewrok (among other places). They would provide a pair of an interface and its default, do-nothing implementation. Everyone would be encouraged to program to the interface, and base their implementations of the interface on its default implementation counterpart (the adapter). This way Swing designers were free to add more methods to their interface without breaking existing implementations.
For reference, see MouseListener interface and MouseAdapter class.

You can extend Animal as a separate interface or an abstract class.
public interface Pet extends Animal {
public void fetch();
}
or
public abstract class Pet implements Animal {
public abstract void fetch();
}

Related

Java Abstraction: abstract class delegates abstractions vs. concrete class uses common abstractions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Say i am implementing a simple interface like Animal. Broadly speaking, there are two ways to go about doing that:
implement the interface's method in the abstract class, and create abstract methods for any implementation specific logic needed.
implement the interface method in the concrete classes, and move the common logic in the abstract class with protected access.
I'd like to understand if-
there are any objective benefits of one way over the other in terms of design.
is it recommended to stick with just one way in a single project (code maintainability/readability).
public interface Animal {
void makeSound();
}
public abstract class BaseAnimal implements Animal {
#Override
public void makeSound() {
//do something which is common for all implementaions
doSomeImplementaionSpecificStuff();
}
public abstract void doSomeImplementaionSpecificStuff();
}
public class Dog extends BaseAnimal implements Animal {
public void doSomeImplementationSpecificStuff(){
//do something specific to a dog
}
}
public abstract class BaseAnimal implements Animal {
public void doCommonStuff() {
//any common logic that can be shared between concrete implementation goes here
}
}
public class Dog extends BaseAnimal implements Animal {
#Override
public void makeSound() {
doCommonStuff();
//do something specific to a dog
}
}
The two ways are not always interchangeable.
Your first example sets a constraint for subclass that requires to implement a specific method that is a part of the makeSound() method.
Using that way couples strongly the implementation of the subclass to which one of the parent class.
Besides, the subclass may still subclass makeSound() as it is not final.
So I would use that way only for very specific scenarios :
to define a factory method that subclass have to define because parent class relies on that (abstract factory)
to define a general algorithm and let subclass to define some specific parts of that algorithm (template method).
In the general case you want to use the code of the second example but by doing BaseAnimal a Animal too :
public abstract class BaseAnimal implements Animal {
public void doCommonStuff() {
//any common logic that can be shared between concrete implementation goes here
}
}
public class Dog extends BaseAnimal implements Animal {
#Override
public void makeSound() {
doCommonStuff();
//do something specific to a dog
}
}
Note that in Java 8, default interfaces rely you from defining the abstract class that only defines common methods :
public interface Animal {
void makeSound();
default void doCommonStuff() {
//any common logic that can be shared between concrete implementation goes here
}
Note also that exposing doCommonStuff() in the API of the abstract class is not necessarily fine. Is client should be able to call it ?
If that is an implementation detail, you could extract it into a support class (AnimalDelegate) and favor composition over inheritance by composing an AnimalDelegate into the Animal subclasses.
If there is a default common way to implement the interface that most subclasses would use, then just implement the overriden method that way in the abstract class. Any subclass that needs it that way can just leave it as is. Any subclass that needs it a completely different way can override and reimplement it entirely. Any subclasses that wants to use the default implementation but then add some stuff to it can override and then call super.makeSound() as part of the implementation.
Don't forget to document exactly what the default implementation is.
The main difference is that you can put logic in the parent class, and create a sort of default method if you don't want to implement all the method of a parent/abstract class.
The interface force you to implement all the methods no matter what.
public abstract class BaseAnimal {
public void doCommonStuff() {
System.out.println("doComon1");
}
public void doCommonStuff2() {
System.out.println("doComon1");
}
public static void main(String[] args) {
SuperDog superDog = new SuperDog();
superDog.doCommonStuff();
}
}
two implementation could be:
public class cat extends BaseAnimal {
#Override
public void doCommonStuff() {
//specific logic
}
#Override
public void doCommonStuff2() {
//specific logic
}
}
public class Dog extends BaseAnimal {
#Override
public void doCommonStuff() {
//specific logic
}
// don't override the doCommonStuff2() method so you have the parent implementation
}
and also, with abstract classes you can make a mix:
public class SuperDog extends BaseAnimal {
#Override
public void doCommonStuff(){
super.doCommonStuff();
System.out.println("do specific after common stuff");
}
}
The last one, can call the parent logic and also add a specific logic. With interfaces you cannot do any of those.
Think about the interface that your abstract class is providing to subclass implementors.
Document the methods that the subclass can use or override. Make sure that the docs tell the subclass implementor what he needs to know to use your base class properly.
Now:
Option 1: In almost all cases this turns out to be a bad idea, because your abstract class is assuming that subclasses will satisfy the Animal interface in a particular way, and will only need to change the bits you expect them to change. Assumptions like that turn out to be wrong eventually. If you document that doSomeImplementaionSpecificStuff, you'll usually find that all the clauses about when that method will be called and what it is expected to do will be embarrassing. That said, sometimes an abstract class like this can be useful if it is a base class that an implementor might use, and not the base class that an implementor is expected to use.
Option 2: This is OK, as long as doCommonStuff is "commonly used stuff" that a subclass implementor can choose to use or not, and not something that a subclass implementor must call, and certainly not something that the subclass implementor must call at a particular time. If you can avoid having state in that abstract class, then you might want to move that common stuff into a utility library.
In all cases the thing to remember is this: When your abstract base is used, it is the subclass implementor that is trying to implement the Animal interface. He gets to make all the decisions about how exactly that is done. Your base class is an offer to help with that in a specific way, which the subclass implementor can take or leave.

Methods of collection frameword [duplicate]

Just as a counterpoint to this question: what is an interface in Java?
An interface is a special form of an abstract class which does not implement any methods. In Java, you create an interface like this:
interface Interface
{
void interfaceMethod();
}
Since the interface can't implement any methods, it's implied that the entire thing, including all the methods, are both public and abstract (abstract in Java terms means "not implemented by this class"). So the interface above is identical to the interface below:
public interface Interface
{
abstract public void interfaceMethod();
}
To use this interface, you simply need to implement the interface. Many classes can implement an interface, and a class can implement many interfaces:
interface InterfaceA
{
void interfaceMethodA();
}
interface InterfaceB
{
void interfaceMethodB();
}
public class ImplementingClassA
implements InterfaceA, InterfaceB
{
public void interfaceMethodA()
{
System.out.println("interfaceA, interfaceMethodA, implementation A");
}
public void interfaceMethodB()
{
System.out.println("interfaceB, interfaceMethodB, implementation A");
}
}
public class ImplementingClassB
implements InterfaceA, InterfaceB
{
public void interfaceMethodA()
{
System.out.println("interfaceA, interfaceMethodA, implementation B");
}
public void interfaceMethodB()
{
System.out.println("interfaceB, interfaceMethodB, implementation B");
}
}
Now if you wanted you could write a method like this:
public void testInterfaces()
{
ImplementingClassA u = new ImplementingClassA();
ImplementingClassB v = new ImplementingClassB();
InterfaceA w = new ImplementingClassA();
InterfaceA x = new ImplementingClassB();
InterfaceB y = new ImplementingClassA();
InterfaceB z = new ImplementingClassB();
u.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation A"
u.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation A"
v.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation B"
v.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation B"
w.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation A"
x.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation B"
y.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation A"
z.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation B"
}
However, you could never do the following:
public void testInterfaces()
{
InterfaceA y = new ImplementingClassA();
InterfaceB z = new ImplementingClassB();
y.interfaceMethodB(); // ERROR!
z.interfaceMethodA(); // ERROR!
}
The reason you can't do this is that y is of type interfaceA, and there is no interfaceMethodB() in interfaceA. Likewise, z is of type interfaceB and there is no interfaceMethodA() in interfaceB.
I mentioned earlier that interfaces are just a special form of an abstract class. To illustrate that point, look at the following code.
interface Interface
{
void abstractMethod();
}
abstract public class AbstractClass
{
abstract public void abstractMethod();
}
You would inherit from these classes almost exactly the same way:
public class InheritsFromInterface
implements Interface
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
public class InteritsFromAbstractClass
extends AbstractClass
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
In fact, you could even change the interface and the abstract class like this:
interface Interface
{
void abstractMethod();
}
abstract public class AbstractClass
implements Interface
{
abstract public void abstractMethod();
}
public class InheritsFromInterfaceAndAbstractClass
extends AbstractClass implements Interface
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}
However, there are two differences between interfaces and abstract classes.
The first difference is that interfaces cannot implement methods.
interface Interface
{
public void implementedMethod()
{
System.out.println("implementedMethod()");
}
}
The interface above generates a compiler error because it has an implementation for implementedMethod(). If you wanted to implement the method but not be able to instantiate the class, you would have to do it like this:
abstract public class AbstractClass
{
public void implementedMethod()
{
System.out.println("implementedMethod()");
}
}
That's not much of an abstract class because none of its members are abstract, but it is legal Java.
The other difference between interfaces and abstract classes is that a class can inherit from multiple interfaces, but can only inherit from one abstract class.
abstract public class AbstractClassA { }
abstract public class AbstractClassB { }
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
The code above generates a compiler error, not because the classes are all empty, but because InheritsFromTwoAbstractClasses is trying to inherit from two abstract classes, which is illegal. The following is perfectly legal.
interface InterfaceA { }
interface InterfaceB { }
public class InheritsFromTwoInterfaces
implements InterfaceA, InterfaceB
{ }
The first difference between interfaces and abstract classes is the reason for the second difference. Take a look at the following code.
interface InterfaceA
{
void method();
}
interface InterfaceB
{
void method();
}
public class InheritsFromTwoInterfaces
implements InterfaceA, InterfaceB
{
void method() { System.out.println("method()"); }
}
There's no problem with the code above because InterfaceA and InterfaceB don't have anything to hide. It's easy to tell that a call to method will print "method()".
Now look at the following code:
abstract public class AbstractClassA
{
void method() { System.out.println("Hello"); }
}
abstract public class AbstractClassB
{
void method() { System.out.println("Goodbye"); }
}
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
This is exactly the same as our other example, except that because we're allowed to implement methods in abstract classes, we did, and because we don't have to implement already-implemented methods in an inheriting class, we didn't. But you may have noticed, there's a problem. What happens when we call new InheritsFromTwoAbstractClasses().method()? Does it print "Hello" or "Goodbye"? You probably don't know, and neither does the Java compiler. Another language, C++ allowed this kind of inheritance and they resolved these issues in ways that were often very complicated. To avoid this kind of trouble, Java decided to make this "multiple inheritance" illegal.
The downside to Java's solution that the following can't be done:
abstract public class AbstractClassA
{
void hi() { System.out.println("Hello"); }
}
abstract public class AbstractClassB
{
void bye() { System.out.println("Goodbye"); }
}
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }
AbstractClassA and AbstractClassB are "mixins" or classes that aren't intended to be instantiated but add functionality to the classes that they are "mixed into" through inheritance. There's obviously no problem figuring out what happens if you call new InheritsFromTwoAbstractClasses().hi() or new InheritsFromTwoAbstractClasses().bye(), but you can't do that because Java doesn't allow it.
(I know this is a long post, so if there are any mistakes in it please let me know and I will correct them.)
Interface is a contract. A simple example is a Tenant and Landlord which are the two parties and the contract is the Rent Agreement. Rent Agreement contains various clause which Tenants have to follow. Likewise Interface is a contact which contains various method (Declaration) which the Party has to implement (provide method bodies).Here party one is the class which implement the interface and second party is Client and the way to use and interface is having “Reference of Interface” and “Object of Implementing class”: below are 3 components:(Explained with help of example)
Component 1] Interface : The Contract
interface myInterface{
public void myMethod();
}
Component 2] Implementing Class : Party number 1
class myClass implements myInterface {
#Override
public void myMethod() {
System.out.println("in MyMethod");
}
}
Component 3] Client code : Party number 2
Client.java
public class Client {
public static void main(String[] args) {
myInterface mi = new myClass();
// Reference of Interface = Object of Implementing Class
mi.myMethod(); // this will print in MyMethod
}
}
An interface in java is a blueprint of a class. It has static constants and abstract methods only.The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java. An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors(Abstract Methods) that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.Since multiple inheritance is not allowed in java so interface is only way to implement multiple inheritance.
Here is an example for understanding interface
interface Printable{
void print();
}
interface Showable{
void print();
}
class testinterface1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
testinterface1 obj = new testinterface1();
obj.print();
}
}
Interface : System requirement service.
Description : Suppose a client needed some functionality "i.e. JDBC API" interface and some other server Apache , Jetty , WebServer they all provide implements of this.
So it bounded requirement document which service provider provided to the user who uses data-connection with these server Apache , Jetty , WebServer .
Interface is the blueprint of an class.
There is one oop's concept called Data abstraction under that there are two categories one is abstract class and other one is interface.
Abstract class achieves only partial abstraction but interface achieves full abstraction.
In interface there is only abstract methods and final variables..you can extends any number of interface and you can implement any number of classes.
If any class is implementing the interface then the class must implements the abstract methods too
Interface cannot be instantiated.
interface A() {
void print()
}
This question is 6 years old and lot of things have changed the definition of interface over the years.
From oracle documentation page ( post Java 8 release) :
In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
Have a look at related SE questions for better explanation:
Is there more to an interface than having the correct methods
What is the difference between an interface and abstract class?
What it is
An interface is a reference type, just like a class is. These are the two main reference types in Java.
What it contains
An interface can contain a subset of what a normal class can contain. This includes everything that is static, both methods and variables, and non-static method declarations. It is not allowed to have non-static variables.
A declaration of a method differs from a normal method in several things; here is one as an example:
[public] [abstract] ReturnType methodName();
These declarations can be marked as public and abstract, as represented with [optional braces]. It is not necessary to do so, as it is the default. private, protected, package-private (aka. nothing) and the final modifier are not allowed and marked as a compiler error. They have not implementation, so there is a semicolon instead of curly braces.
As of Java 8, they can hold non-static methods with an implementation, these have to be marked with the default modifier. However, the same restrictions as to the other modifiers apply (adding that strictfp is now valid and abstract is no more).
What it's useful for
One of its uses is for it to be used as a face for a service. When two parties work together to form a service-requester & service-provider kind of relationship, the service provider provides the face of the service (as to what the service looks like) in the form of an interface.
One of the OOP concept is "Abstraction" which means to hide away complex working of the systems and show only what is necessary to understand the system. This helps in visualizing the working of a complex system.
This can be achieved through interface where in each module is visualized (and also implemented) to work through interface of another module
An interface is a class-like construct that contains only constants and abstract methods (Introduction to java programming, n.d.). Moreover, it can extend more than one interface for example a Superclass. Java allows only single inheritance for class extension but allows multiple extensions for
interfaces(Introduction to Java programming, n.d.) For example,
public class NewClass extends BaseClass
implements Interface1, ..., InterfaceN {
...
}
Secondly, interfaces can be used to specify the behavior of objects in a class. However, they cannot contain abstract methods. Also, an interface can inherit other interfaces using the extends keyword.
public interface NewInterface extends Interface1, ... , InterfaceN {
}
Reference
Introduction to Java Programming. Interfaces and Abstract classes (n.d). Retrieved March 10, 2017 from https://viewer.gcu.edu/7NNUKW
In general, we prefer interfaces when there are two are more implementations we have. Where Interface is acts as protocol.
Coding to interface, not implementations Coding to interface makes loosely couple.
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. for more details
From the latest definition by Oracle, Interface is:
There are a number of situations in software engineering when it is
important for disparate groups of programmers to agree to a "contract"
that spells out how their software interacts. Each group should be
able to write their code without any knowledge of how the other
group's code is written. Generally speaking, interfaces are such
contracts.
For example, imagine a futuristic society where computer-controlled
robotic cars transport passengers through city streets without a human
operator. Automobile manufacturers write software (Java, of course)
that operates the automobile—stop, start, accelerate, turn left, and
so forth. Another industrial group, electronic guidance instrument
manufacturers, make computer systems that receive GPS (Global
Positioning System) position data and wireless transmission of traffic
conditions and use that information to drive the car.
The auto manufacturers must publish an industry-standard interface
that spells out in detail what methods can be invoked to make the car
move (any car, from any manufacturer). The guidance manufacturers can
then write software that invokes the methods described in the
interface to command the car. Neither industrial group needs to know
how the other group's software is implemented. In fact, each group
considers its software highly proprietary and reserves the right to
modify it at any time, as long as it continues to adhere to the
published interface.
[...] An interface is a reference type, similar to a class, that can
contain only constants, method signatures, default methods, static
methods, and nested types. Method bodies exist only for default
methods and static methods. Interfaces cannot be instantiated—they
can only be implemented by classes or extended by other interfaces.
The most popular usage of interfaces is as APIs (Application Programming Interface) which are common in commercial software products. Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product.
An example could be a package of digital image processing methods that are sold to companies making end-user graphics programs.
The image processing company writes its classes to implement an interface, which it makes public to its customers. The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. While the image processing company's API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.
Check out to learn more about interfaces.
In addition to what others have mentioned and by illogical comparison
it's a frame work for wrapping methods so they can be stored in
variables.
Thus on the fly you can equate the interface variable to be equal to any method or collection of methods atleast in this sense, a good reason you would usually want to do that is to escape repetitive logic that will definitely be an enemy of progress within the half life of your code at any decaying rate, be careful with the scenario below user discretion is advised.
SCENARIO
You have a game with a drawSillyThings() method in a SoulAvenger class, that has to draw some frames or sprites. Now drawSillyThings() has a list of other methods it needs to call in other to draw a metamorphed glorified-soul-ranger after user kills the grim-reaper in level 5k, i.e. drawSillyThings() needs to call either of inviteTheGrimReaper(), drawUpperCut(), drawTotalKO(), drawVictoryAndGlorifiedRanger(), drawDefeatAndMockery(), drawFightRecap() and drawGameOver() whenever the right situations arise during the gaming experience but all these would result in unwanted logic in drawSillyThings() which might slow the game i.e.
public static class SoulAvenger{
public SoulAvenger(){
//constructor logic
}
private void loadLevel5k(){...}
private void dontAllowUserWinOnTime(){...}
private void loadGrimReaperFight(){...}
private void drawSillyThings(){
... //unaccounted game logic
while(fighting_in_level_5k){
while(soul_ranger_has_enough_lives){
if(game_state=fight)inviteTheGrimReaper();
else if(game_state=medium_blows)drawUpperCut();
else if(game_state=heavy_blows)drawTotalKO();
else if(game_state=lost)drawDefeatAndMockery();
else if(game_state=won)drawVictoryAndGlorifiedRanger();
else if(game_state=end)drawFightRecap();
}else drawGameOver();
}
}
}
The problem here is the loop-nested boolean checks that have to be performed each time while the soul-ranger is still alive where as you could just have an alternative class which makes sure drawSillyThings() doesn’t need a game_state to be checked each time in order to call the right method but to do that you ‘ld need to kinda store the right method in a variable so that subsequently you can kinda variable = new method and also kinda variable.invoke(). If that wasn’t something have a look
public static class InterfaceTest{
public interface Method{
public void invoke();
}
public static void main(String[] args){
//lets create and store a method in a variable shall we
Method method_variable=new Method(){
#Override
public void invoke(){
//do something
}
};
//lets call or invoke the method from the variable in order to do something
method_variable.invoke();
//lets change the method to do something else
method_variable=new Method(){
#Override
public void invoke(){
//do something else
}
};
//lets do something else
method_variable.invoke();
}
}
This was probably what the guys at oracle had discovered was missing from Java several years before rumors of some developers planning a massive protest surfaced on the web but back to the SoulAvenger, as the gameplay occurs you would definitely just want to kinda have a variable be equated to give the right method to be invoked in drawSillyThings() in order to run things in a silly manner therefore
public static class SoulAvenger{
private interface SillyRunner{
public void run_things();
}
...//soul avenging variables
private SillyRunner silly_runner;
public SoulAvenger(int game_state){
//logic check is performed once instead of multiple times in a nested loop
if(game_state=medium_blows){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawUpperCut();
}
};
}else if(game_state=heavy_blows){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawTotalKO();
}
};
}else if(game_state=lost){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawDefeatAndMockery();
}
};
}else if(game_state=won){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawVictoryAndGlorifiedRanger();
}
};
}else if(game_state=fight){
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawFightRecap();
}
};
}
}
private void loadLevel5k(){
//an event triggered method to change how you run things to load level 5k
silly_runner=new SillyRunner(){
#Override
public void run_things(){
//level 5k logic
}
};
}
private void dontAllowUserWinOnTime(){
//an event triggered method to help user get annoyed and addicted to the game
silly_runner=new SillyRunner(){
#Override
public void run_things(){
drawDefeatAndMockery();
}
};
}
private void loadGrimReaperFight(){
//an event triggered method to send an invitation to the nearest grim-reaper
silly_runner=new SillyRunner(){
#Override
public void run_things(){
inviteTheGrimReaper();
}
};
}
private void drawSillyThings(){
...//unaccounted game logic
while(fighting_in_level_5k){
while(soul_ranger_has_enough_lives){
silly_runner.run_things();
}
}
}
}
Now the drawSillyThings() doesn’t need to perform any if logic while drawing because as the right events gets triggered the silly_runner gets equated to have its run_things() method invoke a different method thus using a variable to store and invoke a method kinda-ish although in the real gaming world(I actually mean in a console) several threads will work asynchronously to change interface variables to run different piece of code with the same call.
An interface in java is a special type of Abstract class, the Interface provided the 100% Abstraction but since the java introduce new features in java 8 the meaning of whole Interface is change. Interfaces are used to tell what should be done. But due to new features now we give implementations of methods in Interface, that changed the meaning of Interface.
In Interface the method is public abstract by default
interface Bird{
void sound();
void eat();
}
Java doesn't provide the multiple inheritances feature mean a class doesn't have two parents, but we extend multiple Interfaces in java.
An interface is a contract between the system and the external environment. More specifically to Java - a contract for a class (for a specific behavior), implemented in a form that resembles a pure abstract class.

Abstract classes and Multiple Inheritance

We can achieve the same functionality as interfaces by using abstract classes, So why java doesn't allow the following code?
abstract class Animals
{
public abstract void run();
}
abstract class Animals1
{
public abstract void run1();
}
class Dog extends Animals,Animals1
{
public void run() {System.out.println("Run method");}
public void run1() {System.out.println("Run1 method");}
}
I know that multiple inheritance can be achieved by using only interfaces but the above code does the same thing as the interfaces would have done it.
This is not allowed because you can do more than this with abstract classes. It wouldn't make sense to allow multiple inheritance, provided you only used an abstract class when you could have used an interface.
It is simpler to only use abstract classes for things you can't do with an interface, in which case you wouldn't be able to use two abstract parent classes.
Note: with Java 8 there is less you can't do with an interface, you can have public instance and static methods with implementations.
In Java 9 you will be able to have private methods in interfaces ;)
This is because abstract classes are still classes, and inheritance is different than implementing an interface. Please see the differences between abstract class and interface. Also please see differences between inplementing an interface and extending a class in Java.
This both questions covers all the information you need to know to understand why you can't have multiple inheritance of abstract classes.
Also let me give you an example why this should not be allowed: Suppose you have the both Animals and Animals1 implementing the same interface IAnimals:
interface IAnimals
{
public string eat();
}
abstract class Animals implements IAnimals
{
public abstract void run();
public string eat(){ return "Animals eating"; }
}
abstract class Animals1 implements IAnimals
{
public abstract void run1();
public string eat(){ return "Animals1 eating"; }
}
If you now define your Dog class as you did:
class Dog extends Animals,Animals1
{
public void run() {System.out.println("Run method");}
public void run1() {System.out.println("Run1 method");}
}
It will have the method eat() too, which is not abstract so it can use it directly. What would be the return of this method for a dog? Which string will be returned, the one with Animals, or the one with Animals1?
This is called the diamond problem, and it is a reason why in some programming languages it is not allowed multiple inheritance.
Java does not support multiple Inheritance. -" One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes. " Source https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
You may find this link useful.
I agree with you(if i understood about what you are talking :) )this is no need of such specific naming conventions.
interface pet
{
public abstract void pet();
}
interface pet1
{
public abstract void pet1();
}
class TestTt implements pet,pet1
{
public void pet()
{
System.out.println("this is method of pet interface");
}
public void pet1() {
System.out.println("this is method of pet1 interface");
}
public static void main(String a[])
{
pet obj=new TestTt();
pet1 obj1=new TestTt();
obj.pet();
obj1.pet1();
}
}
Now, Here if abstract class allows me to create object .then, i can create 2 different references for 2 abstract classes as in interface i can do.
If so, do i need Interfaces...?
In ABSTRACT class,we can't extends multiple abstract classes at a time.
but
In INTERFACE, we can implements multiple interfaces at time.
Therefore , interfaces are used to achieve multiple inheritance in java.

Java Interface\abstract class constriction

Today, our team has the problem.
There is a class AClass that implements the interface AInterface. To date, we need to introduce a new entity(BClass) that would use only part of the interface A.
The first thing about which we think - split interface AInterface into 2 components (composition)
The problem is that the logic AClass->AInterface - is a model prom pattern MVC. And we extremely do not want to cut it into several interfaces.
We know that Java provides a mechanism for inheritance to extend a class or interface.
But is there any way to constrict the implementation? Or maybe exist another way?
Note : we doesn't want use UnsupportedMethodException. Our goal - clean API.
Update :
Next solution - not for us.
GOAL :
Put your restricted subset into one interface, and have the larger interface extend it. Then have A implement the child (larger) interface, and B implement the parent (smaller) one. Then both A and B implement the smaller interface, while only A implements the larger. Use the smaller interface for coding to whenever you can.
public interface AInterface {
void add();
void remove();
}
public interface ASubInterface extends AInterface {
void invalidate();
void move();
}
public class AClass implements ASubInterface { /* 4 methods */ }
public class BClass implements AInterface { /* 2 methods */ }
The very fact that you have a usecase which only requires half of the methods exposed in the original interface tells you that you can further break that interface down. If you think about the design - how do your objects behave in your usecase scenarios, will tell you how it should be designed.
Just by looking at the names of the methods you have given, I'd expect them to be 2 different interfaces where AClass implements both the interfaces while BClass only implements the second interface.
You cannot "disable" polymorphism in certain cases, it's a major feature of the Java language.
If BClass shouldn't have those methods, then it shouldn't implent the interface.
AClass does more than BClass, so it should be another type. Why would you want them to be interchangeable?
On another note, many libraries use UnsupportedMethodException (like even the Java SDK with List collections). It just needs to be documented properly. So if you need ro use that to achieve your goal, go for it.
Your needs seem a little strict but perhaps a abstract class could help.
public interface AInterface {
public void add();
public void remove();
public void invalidate();
public void move();
}
public abstract class BBase implements AInterface {
#Override
public abstract void add();
#Override
public abstract void remove();
#Override
public void invalidate() {};
#Override
public void move() {};
}
public class BClass extends BBase {
#Override
public void add() {
}
#Override
public void remove() {
}
}
Here I create a BBase which stubs out the two methods you want removed but leaves the other two abstract. BClass demonstrates how it would be used.
You can do this if you compile AClass and BClass separately. I.e. compile AClass with the full version of the interface, then modify the interface (remove the methods) and compile BClass with this modified version of the interface.
P.S. By no means this is a painless approach.

Is there any reason for an empty concrete method in an abstract class?

I was recently looking through some open source code PicketLink code. If you take a look at this class, you'll see a number of concrete methods in an abstract class that do nothing. Is there any purpose whatsoever for this?
I thought about two things:
If the method needs to be overriden by subclasses and not defined in the parent abstract class, why not simply make it abstract?
If only some of the child classes actually need to implement the method, wouldn't this indicate the need for a restructuring of the class hierarchy so that children are not forced to have methods that are not applicable?
While not the most common case, sometimes it is handy in the context of a template method. In this case there is a method that defines the flow, leaving the concrete implementation of some parts to its subclasses. In some cases a default concrete behavior is to do nothing, leaving the concrete method in the base class empty, but allowing customization in the subclass by overriding it.
HTH
Personally I think it is a code smell.
Like you say, unless they have some base functionality - which they don't, they should be abstract, forcing derived classes to provide implementation.
If some derived classes shouldn't have an implementation for these methods, then there's probably something wrong with the design.
Consider this:
public abstract class Animal
{
public abstract string Speak();
}
public class Dog : Animal
{
public override string Speak()
{
Console.WriteLine("Woof");
}
}
public class Cat : Animal
{
public override string Speak()
{
Console.WriteLine("Meow");
}
}
All fine so far, but what if you want to add an animal that doesn't speak?
public class Ant : Animal
{
public override string Speak()
{
// do nothing - ants don't speak.
}
}
This in my opinion is bad. Someone might do this (what you have described).
public abstract class Animal
{
public string Speak()
{
// not abstract because not all derived animals speak.
}
}
This in my opinion, is better, but still not great. What I would like to see in this situation is either Speak be moved to an interface and only the animals that can speak implement it, or something like this.
public abstract class Animal
{
}
public abstract class Mammal : Animal
{
public abstract string Speak();
}
public class Dog : Mammal
{
public override string Speak()
{
Console.WriteLine("Woof");
}
}
public class Cat : Mammal
{
public override string Speak()
{
Console.WriteLine("Meow");
}
}
public class Ant : Animal
{
}
Building off of Andres Fortier's answer, you will also see this pattern a lot in Swing, with the various EventListener Adapter classes. For example, MouseAdapter provides corresponding empty methods for each listener method. This allows the interface to define all relevant methods, but implementations to extend the corresponding adapter and only override a single method they care about, instead of being forced to provide empty bodies for all other interface methods.

Categories

Resources