best way to seperate common methods - java

I have some common methods for two classes and maybe for others in the future. Therefore I do not want to copy same methods in all classes. I thought to create a utility class and put these methods inside and send the necessary data as a parameter. But I read about using utility class violate OOP.
As a second, I was thinking to apply strategy pattern but I do not need to change behaviour of the method in the runtime, it will work same for both classes therefore it looks it does not suit to my problem.
Do you have any idea what could be the best approach for this situation or which design pattern could be applied?

It's not bad to violate OOP for something that is really a utility class.
Almost all frameworks (spring, hibernate you_name_it) do that to some extend.
Furthermore, if you later plan to support your code, composition is much easier to refactor / support than to maintain inheritance in your classes.

public class Baseclass
{
public Baseclass(){
//init baseclass;
}
public void commonMethod(){
//do stuff;
}
}
public class AnyObject extends Baseclass
{
public AnyObject(){
super();
}
}
Simple example

Related

How to implement a feature into two unrelated classes

I was assigned to a project, and it is my job to implement a feature to the already existing system. This functionality needs to be added to two seperate classes. Both of these classes extend the same super class, but it does not make sense to add the feature to this superclass. What is the best way I can implement the same functionality into these two seperate classes without too much code duplication. The simple way would be implementing this functionality into a static class and then using the static methods in the two classes that need this extra functionality, but that sort of seems like bad design.
Is there any sort of design I can use to implement something like this, or is me running into this problem just showing a larger issue in the hierarchy that should be fixed rather than try to work on top of it?
Java does not have stand-alone "static" classes, so that's a non-starter since it's not even possible. As for use of static methods, that's fine if you're talking about stateless utility methods.
Myself, I guess I'd solve this with composition and interfaces:
Create an interface for the functionality that I desire
Create concrete instance(s) of this interface
Give the two classes fields of the interface
Plus getter and setter methods for the interface.
If the classes had to have the new behaviors themselves, then have them implement the interface, and then have these classes obtain the behaviors by "indirection" by calling the methods of the contained object in the interface methods.
I'm sorry that this answer is somewhat vague and overly general. If you need more specific advice from me or from anyone else here, then consider telling us more of the specifics of your problem.
Determine what common features of these two classes the new functionality relies on. Then, extract those features to an interface, modify the two classes to implement that interface, and put the new functionality code in its own class (or possibly a static method somewhere, e.g. NewFeature.doTheThing(NewFeaturable toWhat)) and make it operate on those interfaces.
If the existing classes have to obtain information from / call methods related to the "new feature", then give them a NewFeature field that is an instance of the new feature class and have them interact with that object. Pseudo-ish code:
interface NewFeaturable {
int getRelevantInfo ();
}
class NewFeature {
final NewFeaturable object;
NewFeature (NewFeaturable object) { this.object = object; }
void doSomething () { int x = object.getRelevantInfo(); ... }
}
class ExistingClass extends Base implements NewFeaturable {
final NewFeature feature;
ExistingClass () { ...; feature = new NewFeature(this); }
#Override int getRelevantInfo () { ... }
void doSomethingNew () { feature.doSomething(); }
}
Be wary of new NewFeature(this) there, as subclasses of ExistingClass will not be fully constructed when it is called. If it's an issue, consider deferring initialization of feature until it is needed.
A lot of the specifics depend on your exact situation, but hopefully you get the general idea.

Why does all the interface methods need to be implemented in a class implementing it in java

I know that it is the purpose of the interface and the class can be declared abstract to escape from it.
But is there any use for implementing all the methods that we declare in an interface? will that not increase the weight and complexity of the code if we keep on defining all the methods even it is not relevant for that class? why it is designed so?
The idea of an interface in Java is very much like a contract (and perhaps seen in retrospect this should have been the name of the concept)
The idea is that the class implementing the interface solemnly promises to provide all the things listed in the contract so that any use of a class implementing the interface is guaranteed to have that functionality available.
In my experience this facility is one of the things that makes it possible to build cathedrals in Java.
What you are critizing is exactly the goal interface achieve.
If you don't want to implement an interface, don't declare your class implementing it.
will that not increase the weight and complexity of the code if we
keep on defining all the methods even it is not relevant for that
class?
When you program against an interface, you want the concrete object behind it to implement all its methods. If your concrete object doesn't need or cannot implement all interface method you probably have a design issue to fix.
When any piece of code receives an instance of an interface without knowing what class is behind it, that piece of code should be assured of the ability to call any method in an interface. This is what makes an interface a contract between the callers and the providers of the functionality. The only way to achieve that is to require all non-abstract classes implementing the interface to provide implementations for all its functions.
There are two general ways to deal with the need to not implement some of the functionality:
Adding a tester method and an implementation that throws UnsupportedOperationException, and
Splitting your interface as needed into parts so that all method of a part could be implemented.
Here is an example of the first approach:
public interface WithOptionalMehtods {
void Optional1();
void Optional2();
boolean implementsOptional1();
boolean implementsOptional2();
}
public class Impl implements WithOptionalMehtods {
public void Optional1() {
System.out.println("Optional1");
}
public void Optional2() {
throw new UnsupportedOperationException();
}
public boolean implementsOptional1() {
return true;
}
public boolean implementsOptional2() {
return false;
}
}
Here is an example of the second approach:
public interface Part1 {
void Optional1();
}
public interface Part2 {
void Optional2();
}
public Impl implements Part1 {
public void Optional1() {
System.out.println("Optional1");
}
}
will that not increase the weight and complexity of the code if we
keep on defining all the methods even it is not relevant for that
class?
Yes you are right it will. That is why it is best practice in your coding to follow the Interface Segregation Principle which recommends not to force clients to implement interfaces that they don't use. So you should never have one "fat" interface with many methods but many small interfaces grouping methods, each group serving a specific behavior or sub-module.
This way clients of an interface implement only the needed methods without ever being forced into implementing methods they don't need.
It may depend on Liskov Substitution Principle
So, having A implements B means that you can use A when B is needed and, to make it work without problems, A must have at least the same methods of B.
Please keep in mind that mine is not a "proper" answer, as it's not based on official sources!
When implementing an Interface,we may not need to define all the method declared in the Interface.We can define the some methods,that we don't need,With nothing inside the body.

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

Choose inheritance or interface to implement design pattern in Java?

I just want to inject some design patterns into my Java code, but I don't know which style to use -- is inheritance or interface preferred? And why?
Design patterns aren't a thing to just randomly inject into your application. They're design-time sorts of things, not parmesan cheese that you sprinkle on your code after it's already baked.
That said, Josh Bloch's seminal Effective Java strongly encourages developers to use interfaces for shared behavior rather than using inheritance. This matches my own experience.
ETA: Among other reasons, if you're implementing an interface, you can easily create a mock of that interface for use in testing without worrying about the rest of the inheritance hierarchy.
Design patterns are not 'injected' into your code - you will first need to notice that your problem is similar to problems solved by many others, and that they have distilled a pattern that solves the problem. The most famous ones are here
also, for whether you want to use inheritance (aka extending), or interface depends. usually interface and composition works better.
The two features are not mutually exclusive. Interface and implements specify types and compatibility with a type. Inheritance allows for sharing code efficiently. In a classic design, the type hierarchy is expressed using interfaces, while code reuse is achieved using inheritance.
I do agree that one should not think about injecting OR using some design patterns. Design patterns are meant to solve very specific problems within in given context.
About interfaces and inheritance:
Interfaces are being used when you need runtime polymorphism. So, you define an interface and you can have multiple different implementations of it. In client code you can just declare reference as an interface type. Now, you dont bother about actual type of the object passed to the client at runtime. You just care about calling a method on the reference.
interface Car {
void startEngine();
void stopEngine();
}
class Maruti implements Car {
public void startEngine() {
System.out.println("Maruti engine started");
}
#Override
public void stopEngine() {
System.out.println("Maruti engine stopped");
}
}
class Porsche implements Car {
#Override
public void startEngine() {
System.out.println("Porsche engine started");
}
#Override
public void stopEngine() {
System.out.println("Porsche engine stopped");
}
}
In above example as a client, you would just declare reference as Car type. And at runtime you can have Maruti object or Porsche object, you dont care about. What you care about is just to call startEngine or stopEngine.
Inheritance is generally used for code re-usability and extensibility. So, you have common code in two classes and both seem to belong to a common type then you can create a parent class (some times abstract) and move the common code in the parent class. This way you can get rid of duplicate code. The other use case is extensability, sometimes you dont have control on the source code of class and still you would like to add/change some behaviour. You can use inheritance and override certain methods.
There is one more thing called "composition" which is a preferable way over inheritance for extensibility.

Java: extending Object class

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.

Categories