Core Java interface reusablity [duplicate] - java

This question already has answers here:
What is the "default" implementation of method defined in an Interface?
(3 answers)
Closed 4 years ago.
A java interface say "TestInterface" having 2 methods method1(), method2() is implemented by 100 different classes. Now I need to introduce a new method in TestInterface without making changes to other classes which already implemented it. How do I achieve it in java?

In my experience, the best way to do this is often to extend your Interface
public interface TestInterfaceEx extends TestInterface
Then, you can add methods to TestInterfaceEx, have the classes you want implement that, and use
if (myinstance instanceof TestInterfaceEx) {
myinstanceEx = (TestInterfaceEx) myinstance;
//...
}
in places where you want to use this new functionality

now from java 8 you can add default method in your interface, that method(default method in the interface) is present in all the classes that will implement it....
Ex :--
public class Java8Tester {
public static void main(String args[]) {
Vehicle vehicle = new Car();
vehicle.print();
}
}
interface Vehicle {
default void print() {
System.out.println("I am a vehicle!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
interface FourWheeler {
default void print() {
System.out.println("I am a four wheeler!");
}
}
class Car implements Vehicle, FourWheeler {
public void print() {
Vehicle.super.print();
FourWheeler.super.print();
Vehicle.blowHorn();
System.out.println("I am a car!");
}
}

From Java8:
For example, if several classes such as A, B, C and D implement an interface XYZInterface then if we add a new method to the XYZInterface, we have to change the code in all the classes(A, B, C and D) that implement this interface. In this example we have only four classes that implement the interface which we want to change but imagine if there are hundreds of classes implementing an interface then it would be almost impossible to change the code in all those classes. This is why in java 8, we have a new concept “default methods”. These methods can be added to any existing interface and we do not need to implement these methods in the implementation classes mandatorily, thus we can add these default methods to existing interfaces without breaking the code.
We can say that concept of default method is introduced in java 8 to add the new methods in the existing interfaces in such a way so that they are backward compatible. Backward compatibility is adding new features without breaking the old code.
The method newMethod() in MyInterface is a default method, which means we need not to implement this method in the implementation class Example. This way we can add the default methods to existing interfaces without bothering about the classes that implements these interfaces.
interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
System.out.println("Newly added default method");
}
/* Already existing public and abstract method
* We must need to implement this method in
* implementation classes.
*/
void existingMethod(String str);
}
public class Example implements MyInterface{
// implementing abstract method
public void existingMethod(String str){
System.out.println("String is: "+str);
}
public static void main(String[] args) {
Example obj = new Example();
//calling the default method of interface
obj.newMethod();
//calling the abstract method of interface
obj.existingMethod("Java 8 is easy to learn");
}
}

Related

How to implement an override method of implemented interfaces with the same signature in java. And give different implementations for each interface [duplicate]

This question already has answers here:
Implementing two interfaces in a class with same method. Which interface method is overridden?
(8 answers)
Closed 12 months ago.
Let's say I have two interfaces InterfaceA and InterfaceB with the same method signature.
InterfaceA:
public interface InterfaceA {
void printInterfaceName();
}
And InterfaceB:
public interface InterfaceB {
void printInterfaceName();
}
And I have a Printing class that is implementing both the interface
Printing class:
public class Printing implements InterfaceA, InterfaceB {
// want to override the printInterfaceName() method such way
// so that it will give an output which given in main method comment
}
And I have a Main class with a main method on it
public class Main {
public static void main(String[] args) {
InterfaceA a = new Printing();
InterfaceB b = new Printing();
a.printInterfaceName(); // this is should print `INTERFACE-A`
b.printInterfaceName(); // and this is should print `INTERFACE-B`
}
}
Since the method is not aware of the context (a.printInterfaceName() or b.printInterfaceName()), it will not be possible to distinguish between both of them and print INTERFACE-A or INTERFACE-B.
As far as I know, neither reflection nor instanceof can do the trick. Having default Methods in the Interfaces wont work either.
Maybe you can write more about your intention, so that a different solution can be suggested?

How can you "embed" an interface in a Java class like in Go?

In Go you do the following:
package main
type Interface interface {
doSomething() error
doAnotherThing() error
}
type MyImplementation struct {
Interface
}
func (i *MyImplementation) doSomething() error {
return nil
}
You can implement some methods of the interface and leave the rest to the embedded interface.
Suppose I want to do the same in Java and partly implement an interface of 20 or more methods but don't want to write out every single method and call my underlying interface.
I don't have control over the interface as it is in a library I'm using.
Is this possible in Java or do I have to write out the whole interface?
Create an abstract class, implementing the interface, to put only some common method implementations, and then create normal classes, extending the abstract class, for remaining specific methods implementations.
Something like this:
//don't touch the interface if its already there
interface Interface {
public void doSomething();
public void doAnotherThing();
}
//use abstract class for common implementations
abstract class PartialClass implements Interface{
#Override
public void doSomething() {
System.out.println("doing someting in common code");
}
//no need to implement all the methods
}
//create classes for specific implementations
class MyImplementation1 extends PartialClass {
#Override
public void doAnotherThing() {
System.out.println("doing another thing in specific code");
}
}
public class Test {
public static void main(String[] args) throws Exception {
Interface object = new MyImplementation1();
object.doSomething();
object.doAnotherThing();
}
}
Output:
doing someting in common code
doing another thing in specific code
No you can't do that in Java.
You can implement only some methods in abstract classes but can't use those as actual implementations (You can't create them with new).
To use a non abstract class as your interface you need to write out every single method and call your underlying instance in each call.

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.

Why should we use interface if we can simply override methods of the superclass or use abstract classes? [duplicate]

This question already has answers here:
What is the difference between an interface and abstract class?
(38 answers)
Closed 8 years ago.
I have two programs one implemented using interfaces and the other implemented using only classes -
I've read that the advantage of using an interface is that it can provide it's own implementation of methods of super class but that can be done using abstract classes or method overriding. What purpose does interfaces serve?
In what kind of hierarchy and situation using interface will be most beneficial?
INTERFACE
interface Shape
{
void area(int x, int y);
}
class Rectangle implements Shape
{
#Override
public void area(int length, int breadth)
{
System.out.println(length*breadth);
}
}
class Triangle implements Shape
{
#Override
public void area(int base, int height)
{
System.out.println(base*height);
}
}
public class ShapeUsingInterface
{
public static void main(String X[])
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();
r.area(5, 4);
t.area(6, 3);
}
}
CLASS
class Shape
{
void Area(int x, int y)
{
System.out.println(x*y);
}
}
class Rectangle extends Shape
{
}
class Triangle extends Shape
{
#Override
void Area(int base, int height)
{
System.out.println((0.5)*base*height);
}
}
public class CalculateArea
{
public static void main(String X[])
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();
r.Area(4, 5);
t.Area(6, 8);
}
}
To explain why interfaces are used, you have to first understand a problem with inheritance. It's called the Diamond Problem. Simply, if a class, D inherits from two classes B and C, and B and C both inherit from the same class A, which implementation of the methods from A does D get?
What we're left with is a method ambiguity that Java does not like! So the way of preventing this is to make sure that D can only ever have one superclass, so it could inherit from either A, B or C, but never more than one. So that prevents the problem, but we lose all of the perks that multiple inheritance offers!
Enter the Interface. This allows us to have the perks of multiple inheritance (referencing the single class as various different types) and still avoid the diamond problem, because the implementing class provides the method. This removes the method ambiguity.
This means that, for example:
public abstract class MyClass {
public void doSomething();
}
public class MyConcreteClass extends MyClass {
public void doSomething() {
// do something
}
}
You can either refer to an instance of MyConcreteClass as
MyClass class = new MyConcreteClass();
or
MyConcreteClass class = new MyConcreteClass();
But never anything else, given this implementation. You can't extend more classes because you'll potentially get the diamond problem, but you CAN include an Interface
public class MyConcreteClass extends MyClass implements Serializable {
}
All of a sudden, you can say..
Seralizable myClass = new MyConcreteClass();
Because myClass is a Serializable. This is excellent for decoupling classes from one another, when a method might not need to know that it is an instance of MyConcreteClass, only that it has a necessary subset of methods.
In short: You can implement many interfaces, but you can only inherit one class.
Interface defines the contract. Say for example:
interface MusicPlayer
{
public void shuffle();
}
Now each class implementing the interface can have their own algorithm for implementing shuffle method, its upto them. Abstract class is similar to interface, where an abstract class defines few methods to be common and leave other methods to be implemented in our own way. Like
abstract class MusicPlayer
{
public void turnOff()
{
//kill the app
}
abstract public void shuffle();
}
And using interfaces you can implement multiple interfaces but only extend a single class.
I would say that in your example Shape should definitely not be class, but interface. You have provided default implementation for area calculation as x*y, hovewer in case of most shapes this implementation is not correct.
If you will add new shape you will inherit method with incorrect implementation. You will have to remember to check all methods in all classes to validate inherited methods. In case of interface you can't make this mistake.
You can see interfaces as a social contract which states that all the classes who implement the interface should define the methods declared in the interface. This creates continuity between all the classes which implement them, and that's awesome if you want all those classes to have the same behaviors. Since an interface does not declare the implementation itself, it leaves that to the class that implements it. This way you create for example many machines which all have a start button, something you would likely want them all to have. Better said required them all to have, the social contract makes sure this is the case since you must implement every method of an interface! That is required by the compiler.
A class which overrides all the methods in of an other class (by extending the class and implementing in on its one) does not truly say that it will always truly keep this promise. The benefit of knowing that the class will be loyal is gone and you obscure the logic behind it. It would be less clear to see if all methods are overridden or not, and that's bad practice. Why not make your logic clear and actually implement the social contract with an interface.
Abstract classes are a little bit different in that they also implement methods, as seen by normal classes, and also work as an interface because they also require that you implement declared but unimplemented methods. In java 8 interfaces can do this too.

Can you call the parent interface's default method from an interface that subclasses that interface? [duplicate]

This question already has answers here:
Explicitly calling a default method in Java
(6 answers)
Closed 8 years ago.
In java 8 I have something like this:
package test;
public class SimpleFuncInterfaceTest {
public static void carryOutWork(AFunctionalInterface sfi){
sfi.doWork();
}
public static void main(String[] args) {
carryOutWork(() -> System.out.println("Do work in lambda exp impl..."));
AImplementor implementsA = new AImplementor();
//carryOutWork(() -> implementsA.doWork());
BImplementor implementsB = new BImplementor();
carryOutWork(() -> implementsB.doWork());
}
}
#FunctionalInterface
interface AFunctionalInterface {
public void doWork();
default public void doSomeWork(){
System.out.println("FOO");
}
}
#FunctionalInterface
interface BFunctionalInterface extends AFunctionalInterface {
#Override
default public void doSomeWork(){
System.out.println("BAR");//Unreachable in same object?
}
}
class AImplementor implements AFunctionalInterface {
#Override
public void doWork() {
doSomeWork();
}
}
class BImplementor extends AImplementor implements BFunctionalInterface {
public void doSomeWork(){
super.doSomeWork();
new BFunctionalInterface(){
#Override
public void doWork() {
}}.doSomeWork();
System.out.println("WUK WUK");
}
#Override
public void doWork() {
doSomeWork();
}
}
Is there a way to call the default functional interface behavior from implementsB without having to create an anonymous inner class and invoking that?
That has a side effect (calling implementsA's method 2 times), what is desired is a call to the parent's implementation, and then have the childs implementation be able to call the child's default implementation, along with some specialization if needed. As you can see calling the parent's implementation is dead easy, but I don't see a way to avoid re-writing the default implementation unless I add a layer of indirection to the class that implements the child interface, and no way to enforce that.
For instance if A unlocked or provided access to a resource say a database, and B unlocks a second resource (another database), I see no way to make code unlock A and then B enforcing this contract through the use of Functional Interfaces, requiring that A and B be called. One level deep you can do it, but N levels deep looks like it's not possible.
I intended to use lambdas to avoid making expensive calls but to enforce a semantic order of operations on users of my library.
This question is not quite the same as "Explicitly calling a default method in Java", as this question is about interfaces N levels deep, not just calling a parent interfaces default method.
You can invoke an inherited interface default method using InterfaceName.super. The rules are the same as for other super method invocations: You can invoke the inherited method that you have overridden, but you can’t directly invoke the method which the inherited method might have overridden. E.g.
interface A
{
void foo();
default void toOverride() {
System.out.println("A");
}
}
interface B extends A
{
default void toOverride() {
A.super.toOverride();
System.out.println("B");
}
}
interface C extends B
{
default void toOverride() {
A.super.toOverride();// does not work
B.super.toOverride();
System.out.println("B");
}
}
class D implements B
{
public void toOverride() {
}
public void foo() {
D.this.toOverride();
B.super.toOverride();
A.super.toOverride(); // does not work!
}
}
But if each overriding method invokes its super method you have a chain of invocations. However, keep in mind that we are talking about interfaces. An implementation can always override a default method without invoking super at all.

Categories

Resources