There must be a better way to code this :( - java

I was told "model an abstract container for database objects that constructs accepting a varargs of children and then exposes some children inspection functionality without code repetition".
This hints to things like "count # of children", "find by identifier", etc.
For simplicity's sake, the code below just has one field from the base abstract DatabaseObject type (i.e. name) but the real code has things like "identifier" and some complex metadata look-up gimmicks.
The idea of this is certainly useful but just looking at what I started to code makes me wanna puke: it's gonna be a Frankenstein of entanglement if I continue along this path. Any way to make this into decent Java? Any design pattern to reference? (Composite comes to mind...)
Premise: the actual functionality to be shared is useful and indeed applicable to any potential nestable types (Schemas have Tables, Tables have Columns, CompositeIndex(es) have sub-Indexes, etc.), especially the identifier look-ups...
... but "there must be a better way". I feel that voice inside me saying "whenever you write code like that, slap yourself in the face".
Help :)
public abstract class DatabaseContainerObject<ChildType extends DatabaseObject>
extends DatabaseObject {
protected List<ChildType> children;
public DatabaseContainerObject(String name, ChildType... children) {
super(name);
this.children = new ArrayList<ChildType>(children.length);
this.children.addAll(Arrays.asList(children));
}
protected List<ChildType> getChildren() {
return Collections.unmodifiableList(children);
}
... count ...
... find ...
... sort ...
... remove ...
...
}

Think about Strategy pattern(http://en.wikipedia.org/wiki/Strategy_pattern). Cause:
decouple data and data operation.
you can change algorithm("count # of children", "find by identifier") at run time.
I guess, it is something like this:
public abstract class DatabaseContainerObject<ChildType extends DatabaseObject>
extends DatabaseObject {
protected List<ChildType> children;
private DataOperator dataOperator;
public Object find(){
return dataOperator.find(children);
}
}
public interface DataOperator{
public <ChildType extends DatabaseObject> find(List<ChildType> childList);
}
public Class GeneralDataOperator extends DataOperator{
public <ChildType> find(List<ChildType> childList){
//implements find;
}
}
Then, you can use dependency injection.

Composite comes to mind very fast, but you should also investigate the Decorator Pattern.
Find clearly goes recursive, but Count e.g. is very limited on leaf objects and much the same on all kind of nodes.

Composite Pattern with suggestions (Skeletal Implementations) from Item 18: Prefer Interfaces to Abstract Classes from Effective Java 2nd Edition.
Define an iterface (EntityCollection) with methods count(), find(), sort(), remove() etc
Abstract Class DatabaseContainerObject implements EntityCollection interface
Schema, Table, CompositeIndex classes extending DatabaseContainerObject and implementing EntityCollection interface. Here Schema, Table, CompositeIndex are *Component*s in Composite Pattern
The advantage is future classes can either extend DatabaseContainerObject or implement EntityCollection

Related

Is Composition pattern good choice in this scenario?

Here is one design dilemma I have...
In my program, I have different kind of entries - numeric, textual, date, image, etc.
My first idea was to have model structured with inheritance like this:
Entry
-- NumericEntry (extends Entry)
-- TextualEntry (extends Entry)
-- DateEntry (extends Entry)
-- ImageEntry (extends Entry)
Then I can have a list of Entry objects, and each object will know how to handle & expose its data through common members (i.e. showData(), makeSummary() etc.) If I want to add new Entry object, I will just add another class with that specific type.
But, java limitations, and also android orm libraries limitations makes this pretty complicated.
So, I have turned to composite pattern, but I am not sure if I am approaching it right.
So, now I have this (pseudocode):
class Entry
{
Type type;
(nullable)NumericEntry numericEntry;
(nullable)TextualEntry textualEntry;
(nullable)DateEntry dateEntry;
(nullable)ImageEntry imageEntry;
public showData()
{
swicth (type)
{
case numeric: ..
case textual: ..
case date: ..
case image: ..
}
}
}
But this seems to me too wired, doesn't it?
What would be right approach in the described scenario?
I think what you're trying to do is legit, but I think the composite pattern is a bit off here. The composite pattern is rather used for hierarchical structures, as far as I know (like directory structures).
Your model seems quite good, using an (abstract) base class, and let the other types extend from it, however I fail to understand why you want to have all the different types of entries in your base Entry class.
If I understand correctly what you want then this would be more logical.
Interface example:
public interface Entry{
// Define all your methods as abstract and define them here
void showData();
}
public class TextualEntry implements Entry{
void showData(){
// Your implementation for textual entries here
}
}
// Repeat this for the other types of entries
You could also consider an abstract class implementation, which can define properties/fields used in all the extended classes. Moreover, you can implement methods in the abstract class which have the same implementation for all extended classes.
Abstract class example:
abstract class Entry{
// Define your properties here that are used in all the other classes
// Define all your methods as abstract and define them here
public abstract void showData();
}
class TextualEntry extends Entry{
// Define new properties here
public override void showData(){
// Your implementation for textual entries here
}
}
// Repeat this for the other types of entries
On http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html they discuss a similar problem.
If I understand your request correctly you can use Composite, but I did not get how you came to pseudo code.
Composite pattern compose objects into tree structures to represent part-whole hierarchies. Group of objects is to be treated in the same way as a single instance of an object.
Component interface defines common method/methods for leafs and composites.
Leaf implements Component interface, but catch is that you can have multiple leaf objects(numeric, text, ...).
Composite implements Component interface, but it is container for leaf objects as well.
So usage can be:
Component leaf1 = new Leaf(); //numeric entry
Component leaf2 = new Leaf(); // text entry
Composite composite = new Composite();
composite.add(leaf1);
composite.add(leaf2);
composite.operation(); // showData()

Is it good practice for a class to implement itself in a generic interface?

Apologies for the question title, I couldn't put this into words easily.
I've just come across this in some code:
public class MyClass implements Message<MyClass> {...}
I understand what it does but I've never seen a class declared in this way before.
The disadvantage I see is that now MyClass is a Message and needs to include implemented methods that are unrelated to its primary purpose.
One advantage I see (other than it reduces the number of other classes I would otherwise need to write) is that for things like Comparable, MyClass would know how to compare itself to other instance, which in turn would make for more concise code.
Is this good practice? Are there any rules-of-thumb?
This is more or less the only way in Java to have an interface with methods that refer to the implementing class itself. So, for example, you might write a binary tree node interface:
interface TreeNode<N extends TreeNode<N>> {
N getLeftChild();
N getRightChild();
void setLeftChild(N node);
void setRightChild(N node);
}
and then you have classes like
class TreeNodeWithInt extends TreeNode<TreeNodeWithInt> {
int value;
TreeNodeWithInt leftChild;
TreeNodeWithInt rightChild;
public TreeNodeWithInt getLeftChild() { return leftChild; }
public void setLeftChild(TreeNodeWithInt newLeft) { leftChild = newLeft; }
...
}
If we didn't have the N type parameter, you would be forced to write unsafe code like
class TreeNodeWithInt extends TreeNode {
int value;
TreeNodeWithInt leftChild;
TreeNodeWithInt rightChild;
public void setLeftChild(TreeNode node) {
// note the dangerous cast!
leftChild = (TreeNodeWithInt) node;
}
}
The key issue here is that interfaces aren't allowed to refer to the type of the class that's implementing the interface, when they describe the input and return types of methods. So instead, you include a "self" generic type parameter. It's a relatively common idiom in code that makes extensive use of generics.
As you've correctly identified, it's frequently used with Comparable specifically, because you should only be able to compare objects to other objects of the same type. Indeed, Collections.sort is specified to take a List<T> where T extends Comparable<? super T>, which means that T is comparable to at least other values of type T, but possibly others as well.
(Finally, as you might expect -- since it's the only way to achieve this behavior, it's not "good" or "bad" practice. That said, the goal of the technique is to avoid writing methods that compile without warnings but can end up throwing ClassCastException, which is itself a good practice.)
It is neither "good practice" or "bad practice".
The real question is whether it accurately models what you are trying to achieve. In some cases it will, in others it won't.
And if a particular use of the "meta-pattern" results in unwanted and / or meaningless methods, then you have a strong case that it is not the right solution.
Are there any rules-of-thumb?
If it doesn't work in a particular use-case, don't use it in that use-case :-)
While my example is phrased in C#, it translates to Java, and makes sense as a useful idiom for doing common tasks for the class, especially for domain classes. That said, it's neither good nor bad practice.
class Product : IEquatable<Product>, ICloneable<Product>, IComparable<Product>
or in Java
class Product implements IEquatable<Product>, ICloneable<Product>, IComparable<Product>
In this example, I can define a product that knows how to check itself for equality with another, clone itself (perhaps in a generic reusable way), compare itself and so on.
I often use something like the above with code generation, putting as much of the generic at the root level as possible, and extending the more specific things at leaf levels.
Good question, and as Stephen C mentioned, this is neither a good or bad practice. In fact, I your description is not really accurate. This is not a case of a class implementing itself, but a class saying that it is the parameter for the parameterized interface it wants to implement.
public class MyClass implements Message<MyClass> {...}
This effectively means that Message is a "parameterized" interface, meaning, the interface itself accepts a parameter. In this case, the parameter just happens to be the same class that is implementing the parameterized class. But it could be something else. Imagine this:
public class UserDAO implements DAO<User> {...}

Should I extend an ArrayList (is-a) or should I include it as a member (has-a)?

I'm making a simple program that maintains a list of numbers, and I want this list to also have a name. Which is the best approach: have my list class extend ArrayList or have it include an ArrayList member? In both cases, there would of course be a "name" String member.
The first approach means I only have to implement a getter & setter for the name, but I think this would tie my class too closely to a particular implementation? For example, if I wanted to later use a Vector, than I would have to change code everywhere.
The second approach would make it easier to change the implementation, but of course becomes quite annoying for now, since I have to implement a bunch of wrappers.
I've read the SO posts regarding inheritance vs. composition, and since my list is a type of ArrayList, I am leaning towards the first approach. However, is there any differences to the discussion because I'm extending a Collection class vs extending a general class? Or am I over-thinking this?
In the long run it's generally better to include as a member than extend. This way it's more explicit what you want to allow, making it easier to test and hold to the contact of the class. If you simply extend ArrayList then it might not always be used as you intended. The trade-off of course is that you'll have to explicitly create pass-through methods for everything you do want to allow. Alternatively (or additionally) you might want to provide a method to get the underlying List, which you could wrap with an immutable collection to safeguard it from changes happening outside of the control of your class.
For the best of both worlds, use a Guava ForwardingList. Here's a simple example:
public class NamedList<E> extends ForwardingList<E> implements RandomAccess {
// could also let the user provide the delegate list
private final List<E> delegate = Lists.newArrayList();
private String name;
#Override protected List<E> delegate() {
return delegate;
}
// constructors, getter, setter
}
By the way, the pitfalls of extending a concrete collection implementation rather than using composition are discuseed in Effective Java item 16 (in 2nd Ed.) "Favor composition over inheritance." One of the several issues mentioned has to do with unexpected behavior related to the interaction between methods in the superclass (e.g. add and addAll).
Guava's Forwarding* classes are an implementation of the solution suggested there.
Neither is better, its a trade-off as you mentioned.
If you do aggregation (has-a) you have to wrap all the functionality of the member you're going to use (i.e implement functions that call them)
If you do inheritance, A lot of functions are added to your new class which might be unneccessary, And you need to implement abstract functions as well.
If you were in a C++ environment, private inheritance would be an option, But here both have pros and cons
Composition - HAS-A. I prefer it for collections of all stripes.
#AbiusX is right there is trade off. But I have asollution for your worry with first approach. Please consider following and let me know what problems are with this approach:
public class MyClass implements List
{
private String name;
private List myList = new ArrayList();
public MyClass(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setName()
{
return name;
}
#Override
public void add(int index, Object element)
{
myList.add(index,element);
}
#Override
public boolean add(Object o)
{
myList.add(o);
}
#Override
public boolean addAll(Collection c)
{
myList.addAll(c);
}
//so on for rest of methods in List interface
}
We can also include Generics if you want to make it type safe for numbers.
Inheriting ArrayList is not a good idea, you need a strong reason to do that. Utility classes like Collections provide the necessary functionality in several flavors, so you really need to add some extra required functionality in order to justify the subclassing, as is a very well-know class.

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

Java: Deriving from a generic List/Collection

I have a little problem understanding the Java language
public class PhonebookEntryList extends List<PhonebookEntry>
{
public PhonebookEntryList(String filename) throws IOException
{
//loadListFromFilename(filename);
}
public void saveListToFilename(String filename) throws IOException
{
//Do something to save it to a file
}
}
I can't do this, because List is a generic Type (of course). I know what that means, but at the moment I can't think of a Solution for this problem.
Can you help me to solve it? Thanx!
No, your only problem is that you're extending an interface; you must implement it instead.
public class PhonebookEntryList implements List<PhonebookEntry>
should work; or you might prefer to extend a concrete class:
public class PhonebookEntryList extends ArrayList<PhonebookEntry>
or
public class PhonebookEntryList extends LinkedList<PhonebookEntry>
You can't do that because List is an interface. But!
You shouldn't extend or implement a List class to make a PhonebookEntryList, it's a design error.
You should do:
public class PhonebookEntryList
{
private List<PhonebookEntry> entries;
public PhonebookEntryList(String filename) throws IOException
{
//loadListFromFilename(filename);
}
public void saveListToFilename(String filename) throws IOException
{
//Do something to save it to a file
}
}
I.e. your PhonebookEntryList should contain a list instead of inheriting it.
List<T> is an interface, not a class, so you can't inherit from it. You can, however, inherit from a generic type, supplying the type argument, if you wish to create, e.g. a collection for a specific type with some behaviour specific only to that type.
Your Problem is that you are trying to extend an interface rather than implement it.
Composition is what you want. Create a class that wrapps a List (or something that iplements that interface)
and add functionality.
Should I mention that List is an Interface and not a Class? Nah. I think you got the point by now.
I would like to point out, however, that it's usually better NOT to embed the persistence mechanism within the list class. There's this thing called the Visitor pattern that works better. By placing the actual persistency code in a seperate class, the overall logical complexity of the app gets reduced (at the expense of an extra class), and your phonebook becomes liberated to be used in places where having dependencies on the persistency mechanism that looked good when you first designed the code don't look so good anymore. For example, if you wanted to make the Phonebook be an item in an ORM-referenced database.
List<T> is an interface.
If you want to extend a class you'll have to choose an implementation (ArrayList<T> maybe): extends ArrayList<PhonebookEntry>
If you want to implement a List change your code to: implements List<PhonebookEntry>
If you look at the JavaDoc for List, you'll see (as others mentioned) that it's an interface, not a class. What you most likely want to do is look on the same JavaDoc page at "All Known Implementing Classes" and you'll see AbstractList. Extend this. Alternatively, extend one of the non-abstract List implementations.
Note: Most of the time when someone starts to extend one of the Java Collection classes, you're going down the wrong route. Usually, it's better to use one of the existing collections in your class and proxy any collections-style requests that you need. Or return an unmodifiable proxy of your collection:
public class MyClass {
private final List<PhonebookEntry> myList = new LinkedList<PhonebookEntry>();
public List<PhonebookEntry> getList() {
return Collections.unmodifiableList(myList);
}
}
Usually, it's best to extend a class only if you intend to have different behavior than the class you are extending. Inheritance is more brittle than composition.

Categories