Allowing classes with different parents to extend class without multiple inheritance - java

My application has the following class:
MyTextField, which extends JTextField.
I, however, need the methods inside MyTextField in the following class:
MyPasswordField, which extends JPasswordField.
Multiple inheritance isn't allowed in Java, and I'd like to avoid to copy-paste 85% of the class because of this. How to overcome this "limitation"?

Use a helper class that defines the shared functionality. Declare a field in each of MyTextField and in MyPasswordField to hold an instance of the helper class. Relay calls to the helper as needed for the shared functionality, which then only needs to be coded once.

Why don't you use Composition instead of Inheritance.
Your MyPasswordField class can contain an instance variable to myTextField, then you can just use the method using your instance and it's methods.
Let me know if I am going on the wrong track and you expect something different.

You can achieve this with the help of a Helper class with static methods, so you don't need keep an instance of the helper class in your testfields classes.

Related

Why don't we have to create object of System or Math classes in java and use them directly?

We use System.out.println without instantiating it or creating object of it. Same goes to Math class and many others (I guess). Is there something special about these classes? Can we use the classes and methods declared within those classes in same fashion? Please help.
You don't have to create objects for the System and Math classes because the methods and variables in those classes are static. This means that they belong to the class itself, not to instances of the class.
For reference see:
Understanding Class Members
Beyond Basic Arithmetic
This is something called 'static' method. In order to invoke static method, you do not need to have an instance of the class.
This also has other side effects such as non-existing 'this' and thus static methods cannot invoke instance methods.
This is mostly used for some sort of utility classes which are often stateless.
Math is a good example for it.
I suggest to read a bit about static methods and static in Java in general.
You don’t need to create object of System and Math class to use it because they have static methods. Static methods belong to the class and thus doesn’t require it to be instantiated.
Although, you can create its object and then also use those methods, but creating a class for static method is of no use.
Why don't we have to create object of System or Math classes in java and use them directly?
Because the methods of Math are declared as static methods, and because System.in / System.out / System.err are static variables.
Is there something special about these classes?
No. Any variables or methods that are declared as static will behave that way.
Can we use the classes and methods declared within those classes in same fashion?
I don't really understand what you are asking there. But, if you are asking if you can create an instance of Math or System so that you can do something like this:
Math myMath = new Math();
myMath.min(1, 2);
No, you can't. Neither of those classes has a public constructor, so you can't new them.
And if you could do that, it would be really bad style!
Reference:
Understanding Class Members
First,you cannot make an instance of the class Math,because it has only a single constructor and it's been marked private and you just can't make an instance of it from outside the class.
Snapshot of the source code of the class Math
Second,you don't need to do that.All of the methods in class Math are static,just use the class name and the dot operator and you can invoke any one of them.
System class can't instantiate/create object because this System class have private constructor.
And it's all members and methods are static, that can be accessible directly by Class name.
this simple and valid answer will help you.
We don't instantiate every other class or method because the JVM(Java Virtual Machine) already loads them into the project and hence, we can use these classes again and again. One such example is the main method. These classes/methods are already predefined for us so there is no need for us to instantiate such classes/methods because they are static.
You don't have to instantiate the object in order to use methods of the math class.
Because to use this methods we don't need object. We can directly invoke this.
These type of classes are called static. Here methods can directly invoked by the class itself.
They are already defined in the JVM. We don't need to instantiate to use methods of this class.

Object vs Extend in Java

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.

Should I create static method or abstract superclass

I am trying to refactor a project in which there are same methods which are spread across various classes. To reduce code duplication, should I move the common code to an abstract superclass or should I put it in a static method in a utility class?
EDIT
Some of the methods are for generic stuff which I believe can be made static. While there are others which refer to attributes of the class, in which case I think it makes more sense to make it as an abstract super class.
Well, I follow a rule: Don't use base class to remove code duplication, use utility class.
For inheritance, ask question to yourself: Does Is-A relationship exist?
Another rule, which most of the times is correct, is: Prefer composition over inheritance
using static utility class is NOT true composition but it can be called a derivation of it.
Apply these rules to your secenrios and take a decision keeping in mind maintanence and scalability. However it will be good if you could add more details to your quesiton.
It depends on what your code is doing. Are they utility methods? Are they specific/specialized class methods? Is this a heavy multithreaded application?
Keep in mind that if you make them static and your application is multithreaded, you will have to protect them w locks. This, in turn, reduces concurrency. In this case, depending on how many threads call that same piece of code, you might consider moving it (the code) to a super class.
Another point to consider may be the type of work these functions do. If that is scattered, you should create a facade / helper / util class with static methods.
As others have mentioned the answer to this depends on the context of the problem and the duplicated code.
Some things to consider
Does the duplicated code mutate the instance of the object. In this case a protected method in a common abstract class
Instead of Static utility class consider a singleton, Static methods can be problematic for pure unit testing although testing frameworks are getting better at this.
Inheritance can be tricky to get right, think about if these objects from the different classes are really related and require some OO re-factoring ? or are they disjoint pieces of domain logic that happen to require similar bits of code.
If it does not use any class members you might do it static!
But you should do it in a abstract class or mother class
If the methods use many fields or methods of the class they should not be static.
If they are something that a subclass might want to modify they should not be static.
If the methods should be part of an Interface they cannot be static.
Otherwise it's your call and you will probably change your mind later. :-)
At first glance, I would say that it would be better to make the common code as a public static method in a public class. This will make the method useful to any class just by using
UtilityClassName.methodName();
This is better then making it a concrete method in an abstract super-class because then you will always need to extend this super-class in all the classes where you want to use this one single method.
But now, as you said that the method's behavior depends on some variables. Now, if it depends on the instance variables of different classes, then better add this method in an interface and let all your classes implement this interface and have their own implementation of the same.
But again if these variables are constant values, then have these constant values in an interface. Implement these interface in your utility class. And again make it a static method in that utility class which will directly use these constants.
For e.g. Consider foll. common code of returning area of a circle.
public interface TwoDimensional{
double PI = 3.14;
}
public class MyUtility implements TwoDimensional{
public static double getCircleArea(double radius){
return PI*radius*radius;
}
}
Here, you can see that method getCircleArea() depends on the radius which will be different for different classes but still I can pass this value to the static method of myUtility class.

How do I override a single method in java class

I am fairly new to java development and wounder how I can modify an existing Android class. I would like to change some of the methods in Notification.Builder class in Android (https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/Notification.java).
Specifically do I want to change getNotification(), but in the new implementation I need access to the private fields (e.g., mWhen, mSmallIcon).
I have tried to extend the class, but then I don't have access to the private fields of the superclass (i.e., mWhen, mSmallIcon).
What is the best practice to change the method, is it to copy the source code and modify it?
Update:
To be more precise: how can I change a single method in an existing class and still have access to the private fields of the existing class?
Thanks for all responses!
You could simply call super.getNotification() in your overriden method and modify the resulting object before returning it.
A private (inner) class, method or field are only referenced from within the class in which it is declared.
But you also can declare your own variables and work with it as you wish
The best practice is not to override methods (from third-party classes which were not designed to be overridden), but to create a new class/method which wraps the third-party class. Google for these: "fragile base class problem", "composition over inheritance".
I have tried to extend the class, but then I don't have access to the private fields of the superclass (i.e., mWhen, mSmallIcon).
In the particular class you're extending there are a limited number of methods that set the values of these fields. You can override those methods to hold onto copies of the values in new fields in your subclass which you can then use in your override of getNotification().
This is something of a hack, and wouldn't be workable with a more complex class.
Another hack is to use reflection and invoke setAccessible(true) on the field objects. This also may not be workable depending on security constraints.
If you say exactly the change you're trying to make, there might be a better way.

Advice needed: static methods in JAVA interface

I have a class that is handling printing the various messages into the console, lets call this class ConsoleMessages.java. This class is public and abstract and all its methods are public and static.
I want to make an interface to this class (lets call it PrintMessages). I mean so, that ConsoleMessages.java will implement PrintMessages.
The thing is, JAVA doesn't support static methods in an interface.
What would you advise me to do?
Create the PrintMessages interface with the methods you desire.
Make ConsoleMessages a class that implements that interface. Change all methods from static to non static.
Enforce ConsoleMessages instantiation as a singleton. This can be achieved in many ways, either doing it yourself or using a Dependency Injection framework.
There is really no strong arguement against static methods in interface. Nothing bad would happen.
An interface can have static fields and static member classes though, therefore static methods can be attached through them, albeit with one extra indirection.
interface MyService
static public class Factory
static public MyService get(...)
return ...;
MyService service = MyService.Factory.get(args);
If you find yourself needing to define interfaces on a utility class then it may be time to revisit your design choices. Your ConsoleMessages class seems to have outgrown its initial use as a dumping ground for 'common utility functions'.
Short answer? Refactoring time.
Interfaces are there to specify methods for objects (which will then be implemented by some class). You have no objects here, thus you need no interface.
Static methods can only be called using the exact class name (or alternatively the name of some subclass), there is no point in using an interface to do this.
So, you have two options:
Throw your interface away and stay with the static methods.
Make all methods (or at least these which should be in the interface) non-static, and your implementing class non-abstract. To call them one then would need an object of the class (implementing this interface).

Categories