How to implement code to multiple classes in Java? - java

I have two classes: JDialog and JFrame (see below). Now I want them to get some extra functionality, but I want the two classes both to extend my code, without writing the code twice. Is there a way to do that?
java.awt.Window » java.awt.Dialog » javax.swing.JDialog
java.awt.Window » java.awt.Frame » javax.swing.JFrame
(PS: Actually, I want to "rewrite" the source code of java.awt.Window, adding extra functionality. I know that's not possible, but that would be a "solution", because if I do so, both JDialog and JFrame would extend my brand new methods.)
Example:
Suppose I want to add the method moveWindowToMagicPositionOnScreen(), moving the window to a user-friendly position on the screen—I know, it's just an example. I want the method to apply to both JDialog and JFrame. Using inheritance, I must write two classes, for example MagicJDialog and MagicJFrame, each implementing the method moveWindowToMagicPositionOnScreen() in exactly the same manner. Well, that's pretty redundant. So I don't want to have the code written twice. In some way, I want one class to use the code of the other class.

The interface / delegate / composition ideas are probably the "cleanest". But an acceptable and arguably simpler alternative is to make a utility class with a static method.
public static moveWindowToMagicPositionOnScreen(Window window) {
// calculate new x and y
window.setLocation(x, y); // or perhaps setBounds()...
}
In practice, I'd probably put the calculation logic into another method, computeMagicPositionOnScreen(). If it makes sense (it may not) this static utility class could actually be a "real" (non-static) class, say MagicPositionCalculator, that might have multiple instances, say one per each screen, one for really large screens, one for power-users, etc...

Unfortunately, Java does not support mixins. The easiest and clearest approach to take here would be to use composition, in which case you only have to write the wrappers twice, but the actual implementation lives in a single location.

Like several others have suggested, prefer composition over inheritance. However, you can create an common interface for your method:
public interface Magic {
void moveWindowToMagicPositionOnScreen();
}
If the code that moves the window is exactly the same create a delegate class:
public class MagicDelegate implements Magic {
public void moveWindowToMagicPositionOnScreen() {
// TODO implement logic
};
}
Then have your two classes implement the Magic interface using MagicDelegate:
public MagicJDialog implements Magic {
private MagicDelegate magicDelegate; // TODO instantiate
public void moveWindowToMagicPositionOnScreen() {
magicDelegate.moveWindowToMagicPositionOnScreen();
}
}
and
public MagicJFrame implements Magic {
private MagicDelegate magicDelegate; // TODO instantiate
public void moveWindowToMagicPositionOnScreen() {
magicDelegate.moveWindowToMagicPositionOnScreen();
}
}
Side note, the code that moves the window is only partially the same, you can either choose to ignore the MagicDelegate class or create a template class with the common parts:
public abstract MagicTemplate implements Magic {
public moveWindowToMagicPositionOnScreen() {
// common logic
implementationSpecificLogic();
// more common logic
}
protected abstract void implementationSpecificMethod();
}
Now, the MagicJDialog class and the MagicJFrame class can extend the MagicTemplate class and implement the implementationSpecificLogic() method.

Try this,
I think you want to apply DRY (Don't Repeat Yourself) design principle and partially LSP (Liskov substitution Principle), if you want some method to be stored in a class, and then use this method from other two classes, then I think prefering composing over inheritance will be a good idea. Cause you will be able to use the desired method without inheriting the methods that you don't want.

Related

Using multiple classes without creating objects of each

I am new to java and stackoverflow
I have
class Assemble()
class Start()
class Ignite()
class Move()
...... There are still 12 classes
I want use methods inside these classes
but
i should not create objects of them
i cannot use extends for all these also
i there any way possible?
Please bare anything silly, i am not able to figure out.
And this is my first question hear.
the finaly class is
class run
{
public void run_simple()
{
// hear i should be able to access all methods of above class
}
}
If you use an object oriented language (as java) the way it is meant, your whole program is about creating and using objects (as mentioned in many comments). There are some valid technical reasons not to create objects and to use static methods ("it's tedious" is not one of them). There are environments that forbid to use inheritance.
Please state these reasons, otherwise we have to assume that you don't understand some basic concepts of object oriented languages and that your "restrictions" must be ignored.
Most "restrictions" of object oriented programming are intended to help you structure your solution/program. If you see them as real restrictions, the structure of your program might very well be bad.
I'd like to give an example on how something like this might look "the OO way". This might not fully match your project, but should show you that creating objects must not be an issue programmer effort wise.
First we need an interface that defines what one of your actions (thats what I call your classes) looks like
interface Action {
public void run();
}
The following classes define the concrete actions. Their constructors might take parameters configuring details on how to execute them. In the run()-method of each class, you program on what an action does when executed.
class Assemble implements Action {
public void run() {...}
}
class Start implements Action {...}
class Ignite implements Action {...}
class Move implements Action {...}
The controller does the "run everything". That's basically your "overhead" for creating objects!
class Controller {
/** Returns a list of the configured action objects. */
public static List<Action> buildActions() {
List<Action> actions = new LinkedList<Action>();
actions.add(new Assemble(parameter)); // or whathever parameters you need
actions.add(new Start(parameter1, parameter2));
actions.add(new Ignite());
actions.add(new Move());
}
/** Build the list of actions and run one after the other. */
public static void main(String[] args) {
List<Action> actions = buildActions();
for (Action action: actions) {
action.run();
// here you could add logging, profiling etc. per Action.
}
}
}

How to inherits/uses methods from multiple classes

Current I have a base class that contains project init and teardown method, and some large number of common methods, and these methods are inherited/used by its subclasses.
Because the based class is getting huge, so I am trying to move these common methods into newly created classes to improve the modularity of the project. And the original base class inherits the methods from those newly created classes. (multiple inheritances?)
Is there any suggestion to refactor this? also need to minimize the impact to the subclasses.. minimal code changes will be perfect..
Base class
-method1()
-method2()
-method3()
-method4()
-method5()
-method6()--------
| |
| |
subclasse1 subclass2
First of all, there is no multi inheritance of classes (only multi inheritance of interfaces) in java.
However in java 8 you can write default implementations of interface methods (see "Default Methods" on docs.oracle.com). But there are some restrictions:
You still can't declare fields in a interface
If you have 2 default implementations of the same method in different interfaces, you still need to override them.
You may be better off using the adapter pattern, i.e. refractor your code to something like this:
public class BaseClass {
private final Adaptee1 adaptee1;
private final Adaptee2 adaptee2;
// ...
public BaseClass(Adaptee1 adaptee1, Adaptee2 adaptee2 /* , ...*/) {
this.adaptee1 = adaptee1;
this.adaptee2 = adaptee2;
//...
}
public BaseClass() {
this(new ConcreteAdaptee1(), new ConcreteAdaptee2() /* , ...*/)
}
public void method1() {
adaptee1.method1();
}
public void method2() {
adaptee1.method2();
}
public void method3() {
adaptee2.method3();
}
public void method4() {
adaptee2.method4();
}
// ...
}
public interface Adaptee1 {
void method1();
void method2();
}
public interface Adaptee2 {
void method3();
void method4();
// ...
}
//...
public class ConcreteAdaptee1 implements Adaptee1 {
//...
}
public class ConcreteAdaptee2 implements Adaptee2 {
//...
}
//...
You could even pass the adapter to the adaptees in the method calls, if you need access to methods in other adaptees as well for example.
But you should check first, if the class can be split into multiple classes in a good way (i.e. the adaptees should be independent). Don't split the class into parts at all cost. If you can't make the adaptees independent, you should keep it as a single class and rely on your IDE instead to navigate the code easier (Code folds, bookmarks, ...)
In Java, one class cannot extend multiple other classes, however it can implement as many interfaces as you'd like. Unfortunately, implementing an interface will not provide the methods you need.
As far as I could think this out, you have the following options:
1) If you don't want to change all your references to the Base class, and the Base class has some methods that are really broad and may apply to many classes, you could put those into one class and have your base class extend that one.
example:
public class SuperBaseClass{
method1()
method2()
method3()
}
public class BaseClass extends SuperBaseClass{
method4()
method5()
method6()
}
You could even create a SuperDuperBaseClass which SuperBaseClass extends to continue the chain as far as you'd like. The problem with this technique is it forces a hierarchical structure to your project.
2) You could split the Base class into multiple other base classes (I would recommend this one). Sort out your methods into categories and put them in appropriately named base classes. For example, throw all your methods which crunch numbers into one class named Algorithms. Put all your methods which tie other classes and functionalities from your project into one class called Tools. Do this until your whole project is sorted. It will clean everything up as much as possible and keep things manageable in the future. The problem with this is you will have to change everywhere the Base class used to be referenced.
3) You could just leave the Base class as it is. Since it's only a supporting file, you shouldn't really have to be digging through that code very often, so it won't hold you back too much that this file gets a little messy.

Clarification needed on Concept of a listener anonymous class in java

I'm new to java. What is the purpose of a listener anonymous inner class design? I heard that anonymous classes are used as listeners in java. And that no one really creates inner classes or even static inner classes. I'm not sure what that means. could some one explain these concepts a bit? Especially this listener design and how its created via an anonymous class.
Thank you in advance.
An anonymous listener would usually look something like this:
myControl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Handle event
}
});
Using an inner class to accomplish the same goal would usually look something like this:
public void init()
{
myControl.addActionListener(new MyActionListener());
}
private class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Handle event
}
}
Now consider what the two would look like in the scope of a much larger program. The anonymous listener is still right there at the spot where you're adding it. The inner class may be somewhere else in the source file entirely. With a good IDE, that difference can be minimized (such as a members browser), but is there really a need for an entirely new class for something you're going to use once?
Of course, depending on the exact needs of your application, a separate class might in fact be a better choice. If, for example, you have many listeners that differ only a little bit, you could construct something along these lines:
public void init()
{
myControl1.addActionListener(new MyActionListener("foo"));
myControl2.addActionListener(new MyActionListener("bar"));
myControl3.addActionListener(new MyActionListener("baz"));
}
private class MyActionListener implements ActionListener
{
private String word;
public MyActionListener(String word)
{
this.word = word;
}
public void actionPerformed(ActionEvent e)
{
// Handle event
System.out.println(word);
}
}
As far as static classes go: in Java, an inner class can be marked static, and all this does is prevent it from having a reference to the instance of the enclosing class. (For example, MyProgram.MyStaticClass would not be able to access any members of MyProgram which weren't static, unless it creates a new instance of MyProgram.) This may help with separation-of-concerns, but doesn't change very much when it comes to listeners.
That's not true, that no one creates named classes to handle events. Yet most of the time event handlers actually are anonymous classes. The reason for that is that anonymous classes offer less code and less files to maintain and it's easier to read a code when you don't have to jump between many small files. Anonymous classes shouldn't be too long (i.e. no more than ~20 lines of code), if they are longer, they should be converted to named classes. Anonymous classes are common in java version less than 8. In java 8 there are Lambda expressions, which are similar to anonymous classes, but they are more compact.
In languages with support for first class functions listeners can be implemented like this:
def myFunction() { //code }
button.onClick(myFunction)
for simplicity some languages has the capability to define anonymous functions (aka lambdas):
button.onClick({ // code})
Are called "anonymous" because don't need a name to reference it, are used in place.
Java don't has first class functions, instead the listener pattern is implemented with a class that implement some interface:
class myListener implements ButtonListener {
public void listen(...);
}
button.onClick(myListener)
Analogous to the anonymous functions, for simplicity, java has the concept of anonymous classes, you can do:
button.onClick(new ButtonListener {
public void listen(..) { //code }
});
Note: this are simple "ilustrative" examples with an invented on the fly api :P
In java 8 first class functions (closures) are introduced, a huge and very good addition to java IMMO.
Inner classes: sometimes is good that one class is defined within the scope of another class, not the most useful java property IMMO, i use occasionally but can live without it in other languages.

When to use Single method Interfaces in Java

I have seen in many libraries like Spring which use a lot of interfaces with single methods in them like BeanNameAware, etc.
And the implementer class will implement many interfaces with single methods.
In what scenarios does it make sense to keep single method interfaces? Is it done to avoid making one single interface bulky for example ResultSet? Or is there some design standard which advocates the use of these type of interfaces?
With Java 8, keeping the single method interface is quite useful, since single method interfaces will allow the usage of closures and "function pointers". So, whenever your code is written against a single method interface, the client code may hand in a closure or a method (which must have a compatible signature to the method declared in the single method interface) instead of having to create an anonymous class. In contrast, if you make one interface with more than one method, the client code will not have that possibility. It must always use a class that implements all methods of the interface.
So as a common guideline, one can say: If a class that only exposes a single method to the client code might be useful to some client, then using a single method interface for that method is a good idea. A counter example to this is the Iterator interface: Here, it would not be useful having only a next() method without a hasNext() method. Since having a class that only implements one of these methods is no use, splitting this interface is not a good idea here.
Example:
interface SingleMethod{ //The single method interface
void foo(int i);
}
class X implements SingleMethod { //A class implementing it (and probably other ones)
void foo(int i){...}
}
class Y { //An unrelated class that has methods with matching signature
void bar(int i){...}
static void bar2(int i){...}
}
class Framework{ // A framework that uses the interface
//Takes a single method object and does something with it
//(probably invoking the method)
void consume(SingleMethod m){...}
}
class Client{ //Client code that uses the framework
Framework f = ...;
X x = new X();
Y y = new Y();
f.consume(x); //Fine, also in Java 7
//Java 8
//ALL these calls are only possible since SingleMethod has only ONE method!
f.consume(y::bar); //Simply hand in a method. Object y is bound implicitly
f.consume(Y::bar2); //Static methods are fine, too
f.consume(i -> { System.out.println(i); }) //lambda expression. Super concise.
// the above could even be more concise
// presenting all the beauty of the recent Java changes
f.consume(System.out::println)
//This is the only way if the interface has MORE THAN ONE method:
//Calling Y.bar2 Without that closure stuff (super verbose)
f.consume(new SingleMethod(){
#Override void foo(int i){ Y.bar2(i); }
});
}
Interfaces with only one (or few) methods is the key to the highly useful Strategy pattern, which is "some design standard which advocates the use of these type of interfaces".
Another common scenario is when you want a callback. Foo calls Bar as an asynchronous task, and when Bar is finished with something, the result is sent back to Foo using a callback -- which can be an interface containing only one method. (An example of this is the many listeners in Android, Event Listeners in Swing...)
Also, if you have two classes that are tightly coupled with one another (let's call them Foo and Bar). Foo uses nearly all of Bar's methods, but Bar only needs some a few of those from Foo. Foo can implement FooInterface which is then sent to Bar. Now the coupling is looser, because Bar only knows about the FooInterface, but does not care about the other methods the implementing class contains.
In what scenarios does it make sense to keep single method interfaces?
In such a scenarios when you need an interface with only one method.
Interfaces are used to encapsulate a common behavior of several classes. So if you have several places in your code where you need to call only limited set of class methods, it's time to introduce an interface. The number of methods depends on what exactly do you need to call. Sometimes you need one method, sometimes two or more, sometimes you don't need methods at all. What matters is that you can separate behavior from implementation.
Favor Composition over Inheritance tutorial of Head First Design Pattern book recommends this approach to add functionality dynamically to a class. Let's take below case:
public interface Quackable {
public void quack();
}
public class Quacks implements Quackable {
public void quack(){
//quack behavior
}
}
public class DontQuack implements Quackable {
public void quack(){
//dont quack
}
}
public class QuackableDuck{
Quackable quack; //add behavior dynamicall
}
So QuackableDuck class can add feature dynamically.
quack = new Quacks();
//or
quack = new DontQuack();
So similarly you can add multiple behavior to the class dynamically.
You create interfaces not according to the number of methods in it but to define behaviour expected by components of your systems to deliver a single responsibility to their neighbors. If you follow this simple principle/rule, you might or might not end up with single method interfaces, depending on the responsibility you are defining. I like to keep tests stupid simple and the application very flexible so I usually have many of those

How do Java Interfaces simulate multiple inheritance?

I am reading "The Java Tutorial" (for the 2nd time). I just got through the section on Interfaces (again), but still do not understand how Java Interfaces simulate multiple inheritance. Is there a clearer explanation than what is in the book?
Suppose you have 2 kinds of things in your domain : Trucks and Kitchens
Trucks have a driveTo() method and Kitchens a cook() method.
Now suppose Pauli decides to sell pizzas from the back of a delivery truck. He wants a thing where he can driveTo() and cook() with.
In C++ he would use multiple inheritance to do this.
In Java that was considered to be too dangerous so you can inherit from a main class, but you can "inherit" behaviors from interfaces, which are for all intents and purposes abstract classes with no fields or method implementations.
So in Java we tend to implement multiple inheritance using delegations :
Pauli subclasses a truck and adds a kitchen to the truck in a member variable called kitchen. He implements the Kitchen interface by calling kitchen.cook().
class PizzaTruck extends Truck implements Kitchen {
Kitchen kitchen;
public void cook(Food foodItem) {
kitchen.cook(foodItem);
}
}
He is a happy man because he can now do things like ;
pizzaTruck.driveTo(beach);
pizzaTruck.cook(pizzaWithExtraAnchovies);
Ok, this silly story was to make the point that it is no simulation of multiple inheritance, it is real multiple inheritance with the proviso that you can only inherit the contract, only inherit from empty abstract base classes which are called interfaces.
(update: with the coming of default methods interfaces now can also provide some behavior to be inherited)
You're probably confused because you view multiple inheritance locally, in terms of one class inheriting implementation details from multiple parents. This is not possible in Java (and often leads to abuse in languages where it's possible).
Interfaces allow multiple inheritance of types, e.g. a class Waterfowl extends Bird implements Swimmer can be used by other classes as if it were a Bird and as if it were a Swimmer. This is the the deeper meaning of multiple inheritance: allowing one object to act like it belongs to several unrelated different classes at once.
Here is a way to achieve multiple inheritance through interfaces in java.
What to achieve?
class A extends B, C // this is not possible in java directly but can be achieved indirectly.
class B{
public void getValueB(){}
}
class C{
public void getValueC(){}
}
interface cInterface{
public getValueC();
}
class cChild extends C implemets cInterface{
public getValueC(){
// implementation goes here, call the super class's getValueC();
}
}
// Below code is **like** class A extends B, C
class A extends B implements cInterface{
cInterface child = new cChild();
child.getValueC();
}
given the two interfaces below...
interface I1 {
abstract void test(int i);
}
interface I2 {
abstract void test(String s);
}
We can implement both of these using the code below...
public class MultInterfaces implements I1, I2 {
public void test(int i) {
System.out.println("In MultInterfaces.I1.test");
}
public void test(String s) {
System.out.println("In MultInterfaces.I2.test");
}
public static void main(String[] a) {
MultInterfaces t = new MultInterfaces();
t.test(42);
t.test("Hello");
}
}
We CANNOT extend two objects, but we can implement two interfaces.
Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.
If you want to combine the functionality of two classes into one - use object composition. I.e.
public class Main {
private Component1 component1 = new Component1();
private Component2 component2 = new Component2();
}
And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.
Here interfaces may come handy - if Component1 implements interface Interface1 and Component2 implements Interface2, you can define
class Main implements Interface1, Interface2
So that you can use objects interchangeably where the context allows it.
It's pretty simple. You can implement more than one interface in a type. So for example, you could have an implementation of List that is also an instance of Deque (and Java does...LinkedList).
You just can't inherit implementations from multiple parents (i.e. extend multiple classes). Declarations (method signatures) are no problem.
You know what, coming from the perspective of a JavaScript dev trying to understand what the heck is going on with this stuff, I'd like to point out a couple things and somebody please tell me what I'm missing here if I'm way off the mark.
Interfaces are really simple. Stupidly, insanely simple. They're as stupidly, insanely simple as people initially think, which is why there are so many duplicate questions on this exact subject because the one reason to use them has been made unclear by people trying to make more of them than they are and there is widespread misuse in every Java server-side code-base I've ever been exposed to.
So, why would you want to use them? Most of the time you wouldn't. You certainly wouldn't want to use them ALL the time as many seem to think. But before I get to when you would, let's talk about what they're NOT.
Interfaces are NOT:
in any way a workaround for any sort of inheritance mechanism that Java lacks. They have nothing to do with inheritance, they never did, and in no way simulate anything inheritance-like.
necessarily something that helps you with stuff you wrote, so much as it helps the other guy write something meant to be interfaced by your stuff.
They really are as simple as you think they are on first glance. People misuse stupidly all the time so it's hard to understand what the point is. It's just validation/testing. Once you've written something conforms to an interface and works, removing that "implements" code won't break anything.
But if you're using interfaces correctly, you wouldn't want to remove it because having it there gives the next developer a tool for writing an access layer for another set of databases or web services that they want the rest of your app to continue using because they know their class will fail until they get the 100% complete-as-expected-interface in place. All interfaces do is validate your class and establish that you have in fact implemented an interface as you promised you would. Nothing more.
They're also portable. By exposing your interface definitions you can give people wanting to use your unexposed code a set of methods to conform to in order for their objects to use it correctly. They don't have to implement the interfaces. They could just jot them down on a piece of notepad paper and double-check that. But with the interface you have more of a guarantee nothing is going to try to work until it has a proper version of the interface in question.
So, any interface not likely to ever be implemented more than once? Completely useless. Multiple-inheritance? Stop reaching for that rainbow. Java avoids them for a reason in the first place and composited/aggregate objects are more flexible in a lot of ways anyway. That's not to say interfaces can't help you model in ways that multiple-inheritance allows but it's really not inheritance in any way shape or form and shouldn't be seen as such. It's just guaranteeing that your code won't work until you've implemented all of the methods you established that you would.
It's not a simulation of multiple inheritance. In java you can't inherit from two classes, but if you implements two interfaces "it seems like you inherited from two different classes" because you can use your class as any of your two intefaces.
For example
interface MyFirstInteface{
void method1();
}
interface MySecondInteface{
void method2();
}
class MyClass implements MyFirstInteface, MySecondInteface{
public void method1(){
//Method 1
}
public void method2(){
//Method 2
}
public static void main(String... args){
MyFirstInterface mfi = new MyClass();
MySecondInterface msi = new MyClass();
}
}
This will work and you can use mfi and msi, it seems like a multi inheritance, but it's not because you don't inherit anything, you just rewrite public methods provided by the interfaces.
You need to be precise:
Java allows multiple inheritance of interface, but only single inheritance of implementation.
You do multiple inheritance of interface in Java like this:
public interface Foo
{
String getX();
}
public interface Bar
{
String getY();
}
public class MultipleInterfaces implements Foo, Bar
{
private Foo foo;
private Bar bar;
public MultipleInterfaces(Foo foo, Bar bar)
{
this.foo = foo;
this.bar = bar;
}
public String getX() { return this.foo.getX(); }
public String getY() { return this.bar.getY(); }
}
Just by the way, the reason why Java does not implement full multiple inheritance is because it creates ambiguities. Suppose you could say "A extends B, C", and then both B and C have a function "void f(int)". Which implementation does A inherit? With Java's approach, you can implement any number of interfaces, but interfaces only declare a signature. So if two interfaces include functions with the same signature, fine, your class must implement a function with that signature. If interfaces you inherit have functions with different signatures, then the functions have nothing to do with each other, so there is no question of a conflict.
I'm not saying this is the only way. C++ implements true multiple inheritance by establishing precedence rules of which implementation wins. But the authors of Java decided to eliminate the ambiguity. Whether because of a philosophical belief that this made for cleaner code, or because they didn't want to do all the extra work, I don't know.
It's not fair to say that interfaces 'simulate' multiple inheritance.
Sure, your type can implement multiple interfaces and act as many different types polymorphically. However, you obviously won't inherit behaviour or implementations under this arrangement.
Generally look at composition where you think you may need multiple inheritance.
OR A potential solution to achieving something multiple inheritance like is the Mixin interface - http://csis.pace.edu/~bergin/patterns/multipleinheritance.html. Use with care!
They don't.
I think that the confusion comes from people believing that implementing an interface constitutes some form of inheritance. It doesn't; the implementation can simply be blank, no behavior is forced by the act or guaranteed through any contract. A typical example is the Clonable-interface, which while alluding to lots of great functionality, which defines so little that's it's essentially useless and potentially dangerous.
What do you inherit by implementing an interface? Bubkes! So in my opinion, stop using the words interface and inheritance in the same sentence. As Michael Borgwardt said, an interface is not a definition but an aspect.
You can actually "inherit" from multiple concrete classes if they implement interfaces themselves. innerclasses help you achieve that:
interface IBird {
public void layEgg();
}
interface IMammal {
public void giveMilk();
}
class Bird implements IBird{
public void layEgg() {
System.out.println("Laying eggs...");
}
}
class Mammal implements IMammal {
public void giveMilk() {
System.out.println("Giving milk...");
}
}
class Platypus implements IMammal, IBird {
private class LayingEggAnimal extends Bird {}
private class GivingMilkAnimal extends Mammal {}
private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();
private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();
#Override
public void layEgg() {
layingEggAnimal.layEgg();
}
#Override
public void giveMilk() {
givingMilkAnimal.giveMilk();
}
}
I'd like to point out something that bit me in the behind, coming from C++ where you can easily inherit many implementations too.
Having a "wide" interface with many methods means that you'll have to implement a lot of methods in your concrete classes and you can't share these easily across implementations.
For instance:
interface Herbivore {
void munch(Vegetable v);
};
interface Carnivore {
void devour(Prey p);
}
interface AllEater : public Herbivore, Carnivore { };
class Fox implements AllEater {
...
};
class Bear implements AllEater {
...
};
In this example, Fox and Bear cannot share a common base implementation for both it's interface methods munch and devour.
If the base implementations look like this, we'd maybe want to use them for Fox and Bear:
class ForestHerbivore implements Herbivore
void munch(Vegetable v) { ... }
};
class ForestCarnivore implements Carnivore
void devour(Prey p) { ... }
};
But we can't inherit both of these. The base implementations need to be member variables in the class and methods defined can forward to that. I.e:
class Fox implements AllEater {
private ForestHerbivore m_herbivore;
private ForestCarnivore m_carnivore;
void munch(Vegetable v) { m_herbivore.munch(v); }
void devour(Prey p) { m_carnivore.devour(p); }
}
This gets unwieldy if interfaces grow (i.e. more than 5-10 methods...)
A better approach is to define an interface as an aggregation of interfaces:
interface AllEater {
Herbivore asHerbivore();
Carnivore asCarnivore();
}
This means that Fox and Bear only has to implement these two methods, and the interfaces and base classes can grow independetly of the aggregate AllEater interface that concerns the implementing classes.
Less coupling this way, if it works for your app.
I don't think they do.
Inheritance is specifically an implementation-oriented relationship between implementations. Interfaces do not provide any implementation information at all, but instead define a type. To have inheritance, you need to specifically inherit some behaviors or attributes from a parent class.
I believe there is a question here somewhere specifically about the role of interfaces and multiple inheritance, but I can't find it now...
There's really no simulation of multiple inheritance in Java.
People will sometimes say that you can simulate multiple inheritance using Interfaces because you can implement more than one interface per class, and then use composition (rather than inheritance) in your class to achieve the behaviors of the multiple classes that you were trying to inherit from to begin with.
If it makes sense in your object model, you can of course inherit from one class and implement 1 or more interfaces as well.
There are cases where multiple-inheritance turns to be very handy and difficult to replace with interfaces without writing more code. For example, there are Android apps that use classes derived from Activity and others from FragmentActivity in the same app. If you have a particular feature you want to share in a common class, in Java you will have to duplicate code instead of let child classes of Activity and FragmentsActivity derive from the same SharedFeature class. And the poor implementation of generics in Java doesn't help either because writing the following is illegal:
public class SharedFeature<T> extends <T extends Activity>
...
...
There is no support for multiple inheritance in java.
This story of supporting multiple inheritance using interface is what we developers cooked up. Interface gives flexibility than concrete classes and we have option to implement multiple interface using single class. This is by agreement we are adhering to two blueprints to create a class.
This is trying to get closer to multiple inheritance. What we do is implement multiple interface, here we are not extending (inheriting) anything. The implementing class is the one that is going to add the properties and behavior. It is not getting the implementation free from the parent classes. I would simply say, there is no support for multiple inheritance in java.
No, Java does not support multiple inheritance.
Neither using class nor using interface. Refer to this link for more info
https://devsuyed.wordpress.com/2016/07/21/does-java-support-multiple-inheritance
I also have to say that Java doesn't support multiple inheritance.
You have to differentiate the meaning between extends and implements keywords in Java. If we use extends, we are actually inheriting the class after that keyword. But, in order to make everything simple, we can't use extends more than once. But you can implement as many Interfaces as you wish.
If you implement an interface, there's a zero chance that you will miss the implementation of all the methods in each interface (Exception: default implementations of interface methods introduced in Java 8) So, you are now fully aware of what is happening with the things that you have embedded to your fresh class.
Why Java doesn't allow multiple inheritance is actually, multiple inheritance makes the code somewhat complex. Sometimes, two methods of parent classes might conflict due to having the same signatures. But if you are forced to implement all the methods manually, you will get the full understanding about what's going on, as I mentioned above. It makes your code more understandable to you.
If you need more info on Java interfaces, check out this article, http://www.geek-programmer.com/introduction-to-java-interfaces/
Between two Java class multiple Inheritance directly is not possible. In this case java recommend Use to interface and declare method inside interface and implement method with Child class.
interface ParentOne{
public String parentOneFunction();
}
interface ParentTwo{
public String parentTwoFunction();
}
class Child implements ParentOne,ParentTwo{
#Override
public String parentOneFunction() {
return "Parent One Finction";
}
#Override
public String parentTwoFunction() {
return "Parent Two Function";
}
public String childFunction(){
return "Child Function";
}
}
public class MultipleInheritanceClass {
public static void main(String[] args) {
Child ch = new Child();
System.out.println(ch.parentOneFunction());
System.out.println(ch.parentTwoFunction());
System.out.println(ch.childFunction());
}
}

Categories