Quick novice question: I want to extend a class as an array, like so
public class Map extends Item[][]
{
}
Is this possible, am I going about it the wrong way? Thanks!
Arrays are weird beasts. The have some properties, like length but they are not a class, so you can't extend them like you are attempting.
I think you are better off using composition, i.e. create a class that contains an Item[][]
and then extend that class (if you need to, having one class might be enough)
Related
I may be wrong as I have not got too much experience with Java, but here is a question.
I have a class which contains many methods (basically it is a simple library).
I create an object of this class let's say MyLibrary obj = new MyLibrary(parameters);
The parameters set up any necessary functionality for the library to run correctly.
Then I can call obj.getSomething/obj.setSomething/obj.createSomething etc etc...
In my main class I really need only one this kind of library object.
Now... Would it be more useful for me not to use it as an object, but put it as extends and then create a function inside of the library like a constructor which I would call manually?
EDIT:
The relation between the one class and MyLibrary is very close. Basically, I have many classes which do similar things but have some different higher layer functionality. So I separated method which must be in all those classes.
It seems it is very similar to shape class and triangle, circle, square example. So MyLibrary is similar to shape which contains all the foundation.
What you described strongly resembles a utility class, similar to Java's Collections. The class has only static methods, and a private constructor to prevent instantiations. This is a well-known idiomatic pattern in Java - you can use it to create your own groups of methods providing related functionality.
You should not extend, or even instantiate, utility classes at all. Starting with Java-5, you can statically import them so that you could use their methods without making an explicit reference to their class.
extends is used when you need an inheritance hierarchy. It seems more logical to put your code in two separate classes here, like you have it now.
Also, if your "library class" does multiple unrelated things, it should probably be split into multiple classes - one for each task.
You should really only use extends when you have a is-a relationship. So, you can think, is my main class a MyLibrary or should my class have a MyLibrary.
From your described problem, it sounds like having MyLibrary is the way to go.
With the limited detail that you have provided, you might want to consider the Singleton pattern.
extends should only be used when one object needs to inherit the characteristics and functionality of another one because they are very closely related. For example, if you have a Shape class, then you would extend Shape to create Circle, Square, and Triangle. Before you use extends you should learn more about inheritence and when you should and should not use it.
I would make this a static class to use. Similiar to javas MATH class API for math class. You can just use the methods of the class without making an object of it.
Well If your class if performing utility functions then you should mark all methods as static and use operations like
MyLibrary.doSomething();
MyLibrary.createSomething();
MyLibrary.getSomething();
But this wont allow you to keep some data members in the class and if you keep them they will be static as well.
I don't think so that extends suits your case.
Also if you want to keep only an object then you should look at Singleton A class for which only one instance can be created.
Assuming you are just using MyLibrary and may not alter it, you should use a wrapper that makes the whole thing a Singleton, as already proposed by Code-Guru.
public class MyLibraryWrapper {
private static MyLibrary instance = null;
private MyLibraryWrapper() {}
public static MyLibrary getInstance() {
if (instance == null)
instance = new MyLibrary();
return instance;
So in your code you would use
MyLibraryWrapper.getInstance().getSomething();
Best way to create singleton in java 1.5 or above is to use ENUM.
public enum Test {
INSTANCE;
}
INSTANCE is the only instance of Test class.
Is there a way to inherit from a baseclass by using the generic type paramater?
public class Extra<BASE> extends BASE
So that Extra is the new class having all the methods of BASE, like
Extra<MyType>
Greetings
edit*******
That is disappointing. I'm moving a project from C++ to JAVA.
In C++ this is possible, sadly I used this a lot in this project.
Is there another way to achieve that:
A class has its own userdata-class. It needs the members of its userdata linked with a special functionality, that is given by an other class. The other class is extending the first userdata-class. I don't want to have the userdata as a data member in the new class,
but really as a part of it.
Like:
userdata-class:
String name;
special-functionality-class: a generic TreeKnot,
The new class then should be a TreeKnot combined with the userdata-class.
What way could I go ?
No, it is not possible you can create something like this
public class Extra extends Base<Base>
But what do you want it is not possible at all!!!!
No, it's not possible. Type templating and inheritance are two completely different concepts.
Is it possible to make a child class that extends ArrayList? If so, how?
You can extend any class that is not final in Java. Having said that, you should avoid inheritance if there is no true is-a relationship. Consider composition for reuse. Read about Liskov substitution principle
Yes you can.
public class MyArrayList<E> extends ArrayList<E>
{
}
However, I'm not sure why you would want to do this.
As many other have said, yes, you can extend class ArrayList, but it is not something that you should normally do; it is not considered good practice in Java.
I'm mainly a Java programmer, but the past months I've also been working on C# code. It seems like it's a common idiom in C# to extend the standard collection classes if you need a collection of a specific type (I actually don't know if it is a common idiom in general - at least the people who wrote the code I'm working with are doing this all the time).
So if they have a class Person and they need a list of persons, they'd create a class PersonList that extends the C# equivalent of ArrayList<Person>.
The common idiom in Java would just to use ArrayList<Person> if you need a list of Person objects and not to create a specific subclass for this.
I'd advise you to stick to the common Java way of doing things, and not create your own subclasses of ArrayList or other collection classes.
ArrayList is not final class and it provides public constructor, so technically it can be extended.
But best practice is delegate rather than extend.
See: Decorator pattern
Just try it out. The class is not final, it's constructor is public, so you can. However, it's probably no good idea for a beginner.
Most of the time, it's no good idea for anyone. Imagine you add some functionality and get ExtList1 extends ArrayList. A college of yours adds a different independent functionality, so you have ExtList2 extends ArrayList. Now you want them both at once and you're out of luck.
Or you need the same feature with a different base list implementation (maybe LinkedList, though it's virtually always wrong to use it). Again, out of luck.
These are all cases when delegation wins. It needn't be more verbose when someone has created the base already.
I'd only inherit from ArrayList, if there was a very good reason for doing exactly this. Maybe some really extreme performance requirements based on proper JMH benchmarks.
As others said, extending java lang data structures is a very bad idea.
However, if you have some logic you want to isolate in a collection class, I would suggest bellow solution:
public class ProductCollection{
ArrayList<Product> products;
public Product getByCode(String code) {
// ... your logic goes here.
}
}
I'm writing (well, completing) an "extension" of Java which will help role programming.
I translate my code to Java code with javacc. My compilers add to every declared class some code. Here's an example to be clearer:
MyClass extends String implements ObjectWithRoles { //implements... is added
/*Added by me */
public setRole(...){...}
public ...
/*Ends of stuff added*/
...//myClass stuff
}
It adds Implements.. and the necessary methods to EVERY SINGLE CLASS you declare. Quite rough, isnt'it?
It will be better if I write my methods in one class and all class extends that.. but.. if class already extends another class (just like the example)?
I don't want to create a sort of wrapper that manage roles because i don't want that the programmer has to know much more than Java, few new reserved words and their use.
My idea was to extends java.lang.Object.. but you can't. (right?)
Other ideas?
I'm new here, but I follow this site so thank you for reading and all the answers you give! (I apologize for english, I'm italian)
If it is only like a "research" project in which you want to explore how such extension would work, you could provide your own implementation of the Object class. Simply copy the existing object implementation, add your setRole method etc, and give -Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar as parameter to the java command. (I will look for api-classes in . before looking in the real rt.jar.)
You should consider using composition rather than inheritence to solve this problem; that way you can provide the functionality you need without using up your "one-shot" at inheritence.
For example, the JDK provides a class PropertyChangeSupport, which can be used to manage PropertyChangeListeners and the firing of PropertyChangeEvents. In situations where you wish to write a class that fires PropertyChangeEvents you could embed a PropertyChangeSupport instance variable and delegate all method calls to that. This avoids the need for inheritence and means you can supplement an existing class hierarchy with new functionality.
public class MyClass extends MySuperClass {
private final PropertyChangeSupport support;
public MyClass() {
this.support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
protected void firePropertyChangeEvent() {
PropertyChangeEvent evt = new ...
support.firePropertyChangeEvent(evt);
}
}
you can extend Object - every class extends it.
you seem to need something like multiple inheritance - there isn't such a thing in Java
if you want to add functionality, use object composition. I.e.,
YourClass extends Whatever implements ObjectWithRoles {
private RoleHandler roleHandler;
public RoleHandler getRoleHandler() {..} // defined by the interface
}
And then all of the methods are placed in the RoleHandler
If you're talking about adding a role to all your objects I would also consider an annotation-based solution. You'd annotate your classes with something like #Role("User"). In another class you can extract that role value and use it.
I think it would need an annotation with runtime retention and you can check, run-time, whether the annotation is present using reflection and get that annotation using getAnnotation. I feel that this would be a lot cleaner than extending all your classes automatically.
I believe there are some frameworks which use exactly such a solution, so there should be example code somewhere.
If you are doing what you are doing, then inheritance is probably not the correct idiom. You may want to consider the decorator pattern, whereby you construct a class that takes as its parameter some other class with less functionality, and adds some additional functionality to it, delegating to the existing class for functionality that already exists. If the implementation is common to many of your decorators, you may want to consider putting that functionality in class that can be shared and to which you can delegate for all your decorators. Depending on what you need, double-dispatch or reflection may be appropriate in order to make similar but not quite the same decorators for a large variety of classes.
Also, as has been pointed out in the comments, String is declared "final" and, therefore, cannot be extended. So, you should really consider a solution whereby you delegate/decorate objects. For example, you might have some object that wraps a string and provides access to the string via getString() or toString(), but then adds the additional functionality on top of the String class.
If you just want to associate some objects with additional attributes, use a Map (e.g. HashMap).
What you really want to do would be monkey patching, i.e. changing the behaviour of existing classes without modifying their code.
Unfortunately, Java does not support this, nor things like mixins that might be used alternatively. So unless you're willing to switch to a more dynamic language like Groovy, you'll have to live with less elegant solutions like composition.
public abstract class MyAbs implements Comparable<MyAbs>
This would work but then I would be able to compare class A and B with each other if they both extend MyAbs. What I want to accomplish however is the exact opposite.
So does anyone know a way to get the generic type to be the own class? Seemed like such a simple thing at first...
Edit:
To explain it a little further with an example. Say you have an abstract class animals, then you extend it with Dogs and ants.
I wouldn't want to compare ants with Dogs but I however would want to compare one dog with another. The dog might have a variable saying what color it is and that is what I want to use in the compareTo method. However when it comes to ants I would rather want to compare ant's size than their color.
Hope that clears it up. Could possibly be a design flaw however.
Most straightforward would be:
public abstract class MyAbs<T> implements Comparable<T>
Perhaps more usefully, you go Enum style:
public abstract class MyAbs<THIS extends MyAbs<THIS>> implements Comparable<THIS>
You may possibly be able to ignore the issue:
public abstract class MyAbs
An external Comparator feels more natural to me (that is to say, don't have a natural order).
Simply implement Comparable<MyAbs> on class B, which if I interpret your question correctly, extends MyAbs. That way, objects of class B can be compared with any objects whose classes extend MyAbs, but not vice versa. However, if what you want is to have the type parameter reflect the concrete class' type, then you should probably pass Comparable a new type parameter.
I.E.:
public abstract class MyAbs<T> implements Comparable<T extends MyAbs>
But this of course has the disadvantage that now your concrete classes need to change their definition to
public class ConcreteClass extends MyAbs<ConcreteClass>
Looks kindof nasty, but it should work. It's probably better to implement Comparable separately on each concrete class.