Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
What's the best practise(design and performance wise) for anonymous classes and static inner classes?
Personally I would like to think that static inner classes provide better encapsulation and should give better performance as they dont have access to finalized variables outside their class. But I've never really questioned this.
I found one post about this but I felt it didn't actually answer the question about, just peoples personal thought about it.
Inner classes (static or not) have exactly the same access to their enclosing class' fields and methods as anonymous classes, the difference between static inner classes (actually called nested classes) and (regular, non-static) inner classes being that the static one need an explicit reference to an instance of the enclosing class to access something. Of course, when you need to do that, it's usually on the instance of the enclosing class that created the inner class, so it's easier and clearer to use a non-static inner class.
Examples:
Inner class (non-static)
class A {
private int field;
private class B {
public void doSomething() {
field++; // Valid
}
}
}
Nested class (i.e. "static inner class")
class A {
private int field;
private static class B {
public void doSomething(A a) {
a.field++; // Valid
}
}
}
Anonymous class
class A {
private int field;
public void doSomething() {
new Runnable() {
#Override
public void run() {
field++; // Valid
}
}
}
}
Whether you use that accessibility is another question. If you do access private fields of the enclosing class, there'll be an accessor generated, so it could impact the performance as the cost of calling a method is not the same as accessing a field, but it will probably be negligible in most cases. You should always write correct code first (both in terms of design and functionality) before doing micro-optimizations not based on any measurement. The JIT compiler does a lot of things for you anyway.
Have look in Java source code Collections and Pattern to have sample (they are in the src.zip in the JDK directory. In Eclipse, you can read the code with inline help
Read a book Effective Java, look for inner class to understand how works static, inner and other useful interface, enum and other classes
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Let's assume that we have an abstract class (let's just call it X) that is inherited by a number of classes (we'll call them A and B for now). Each class that inherits from X does similar, but slightly different things, so while the implementation of each of their public methods might be slightly different, they can all use the same helper functions to avoid duplicating code. However, it makes no sense for any of these helper functions to be accessed by any class that is not a subclass of X.
Furthermore, what if there are a number of helper functions which are only meant to be used inside of classes that extend X, but need to have a slightly different implementation in each class?
Here's an example:
public abstract class X {
public abstract void doStuff();
int helperFunction(int a, int b) {
return a + b;
}
abstract void secondHelperFunction(int x);
}
public class A extends X {
#Override
public void doStuff() {
//do some stuff
helperFunction(a, b);
//so some other stuff
}
#Override
void secondHelperFunction(int x) {
//implementation A
}
}
public class B extends X {
#Override
public void doStuff() {
//do some different stuff
helperFunction(b, a);
//do other stuff
}
#Override
void secondHelperFunction(int x) {
//implementation B
}
}
(This example is obviously very simple, I'm just trying to get my point across)
My question is, what would be the best way to do this? For example, what access modifier should be used for the helper functions? Obviously private isn't an option, since then subclasses wouldn't be able to use it. Default and protected sound like a better choice, but they still allow non-subclasses to use these functions, as long as they are in the same package as X. Would the best solution to this issue then be to enclose X and all classes that inherit from it in their own package, separate from the rest of the program? Or should one perhaps look into another form of abstraction, e.g. interfaces? (Although I cannot think of a way to deal with this using interfaces in particular)
A couple of options for you to consider:
Use protected. You are correct that this does not prevent other classes within the same package from calling the method. But is that really a problem? The idea of a package is to gather related classes together and control the interface through which they are called. Access modifiers are a relatively coarse control mechanism that are designed primarily to help humans avoid errors when coding.
Put the helper functions in a separate class and use composition rather than inheritance. You could still override methods to provide different behaviours. The downside is you will need to pass in any values required. But this isn't necessarily a bad thing as it makes the dependencies clear.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have developed a Java Program which contains certain static variables that are used in all the classes.
Now, I want to store those variables at a single platform, which I can refer to call from any class rather than declaring them again & again.
I have researched on the internet and found some good solutions like declaring them in an interface and implementing that interface in my classes.
Also, I can write a separate class and call those variables using the object of that class.
Can anyone suggest the better solution? or which one is better between these two? please explain :)
It kind of depends on what you mean by "variables" if you mean global mutable state, you should probably either use a Singleton pattern, or even better, redesign your application in such a way as to eliminate global mutable state. (Encapsulation)
If all your static variables are final, or effectively final (for instance loaded from environment variables at run time), then wrapping them in a class (with a private Constructor, since you do not want to be able to create objects of the class that only has static members) is probably the best solution.
Interfaces are designed to describe behavior, rather than state, so unless you have a contract described in it, it doesn't seem useful to have it as an interface, and could potentially lead to confusion down the road.
1:- Create an enum class like this,
public enum YourClassName{
// these are your three varible
VARIABLE1("val1"), VARIABLE2("val2"), VARIABLE3("val3"),;
private String value;
YourClassName(String value) {
this.value=value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
2:- Once you have an enum class with some variable then you can call from every class like this,
YourClassName.VARBIABLE1.getValue();
this will help you and i think its a good way.
Well to further work on #sleepToken answer there can be multiple ways to what you are looking to do. Again these approaches may depend on the design and at times may totally be different than what is being followed in the code base that you are working on.
For instance in most cases I have seen a convention that constants are defined in an Interface in java and that interface is hardly ever implemented. You can have multiple of these interfaces as well. Like one interface for storing constants related to user and may be another for the constants related to the system
IUserConstants.java
ISystemConstants.java
Now this is totally up to you to decide the names and what these interfaces will hold. Since these are constants you will define in them they are supposed to be public and static and at times you will make them final as well but make sure that you know the difference between runtime and compile time constants. Again this is something you will have to decide about.
Further more public static final are redundant for interfaces. This link just got my attention.
You can check this sample interface
public interface IConstants{
public static final int TIME=10;
public static final String CONFIG_STRING=SomeClass.LoadValue();
}
Another approach I have seen is to use an abstract class that contains all the constants which are static and public and if you want to make sure that it is not further used for implementation you can use a private constructor although I am not sure why this was used because at times legacy code that comes in front hardly makes sense.
public abstract class IConstants
{
public static final int TIME = 10;
public static final String CONFIG_STRING = SomeClass.LoadValue();constant
private IConstants()
{
throw new AssertionError();
}
}
I hope this helps you
You can refer to static variables from any class... (assuming they are not private): just do ClassName.variable.
The better option is to not use static variables as global variables. Use getters and setters to pass values.
The interfaces solution is hacky and I have used it before - but that is also not ideal. Implementing a constants interface is considered bad practice.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am on a new project, and the legacy java code is filled with classes that are using a mix of private static methods, and public static methods.
It's very hard to follow.
For example:
public Car {
private static checkGas(){
..
}
public static startCar(){
checkGas();
}
}
Is there some design pattern I never heard of that would make this applicable?
I've always used public static methods on "helper" classes that do not need Util.caculate(..), and in the above "Car" example I wouldn't have use any private static or public static methods... just private and public methods.
You generally want to limit access as tightly as possible, so if you have a utility class with some public static methods and some static helper methods that they call, those helper methods should be private.
This is not fundamentally different than writing non-static private helper methods to support non-static public methods.
I wouldn't call this a design pattern, so much as a good general practice.
Don't make things public unless you have to. Once a method is public, you can't modify its signature without breaking everything that uses it.
Edit
Regarding the best place to put static methods, I'd rather put them on the class they're designed to help, rather than aggregate random static methods in a "Util" class.
A good example of this would be the Integer class, which can be instantiated to represent a numerical value, but also has many static helper methods like compare, max, parseInt, etc.
Utility classes should be for things that are truly generic, such as the Math class.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Consider that I have a class named Validation with five methods. All the methods are very complex and large. In a certain part of my application, I need to create a Validation object, but I'll only be using one method from that object. I could make the method static to fulfill my purpose, but for the rest of the application to keep working, those methods should be non-static.
So is there a way that I can create an object of a class containing only one of the non-static methods?
No.
About the best you can do (to answer the question as asked) is make the method protected and have a subclass of Validation which extends it. Then, if all the other methods are private, that object will only have the one protected one.
It's kind of a bad situation, though. More than likely, if you're trying to do this, you're either trying to optimize for no reason or you have a bad design somewhere.
e.g.,
public class Validation {
private void method1() {}
private void method2() {}
protected void method3() {}
private void method4() {}
}
...
public class RestrictedValidation extends Validation { }
...
public static void main(String[] args) {
RestrictedValidation validation = new RestrictedValidation();
validation.method1(); //compiler error
validation.method2(); //compiler error
validation.method3(); //success
validation.method4(); //compiler error
}
But yeah. I can't think of a single valid use-case for this.
You can solve this by way of inheritance where ValidationA would contain common methods used by most clients (here your one particular method), and a ValidationB class which extends ValidationA and add more specialized methods.
Or depending of the situation, it could be 2 completely different objects.
No there is no such way. An object consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.
what you is saying is create a person object(whose has already defined behaviour of walking and running) but he should only walk and not run. It does not make sense.
Jeff Gohlke provided a good solution to it
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
What's better to use in Java: a singleton or a class with all static members? Or does it not matter?
For example, I want to access an X class from different classes, but the X class has to contain similar values for all classes which use it.
There are some cases, where static classes makes sense than Singleton. You can see the example of java.lang.Math. This is not singleton -. its just providing us a bunch of static methods.
If your class is not maintaining any state, and just providing global access to some methods, then you should go with using static class, as static methods are faster than Singleton, because of static binding during compile time. Remember you cannot use polymorphism with static methods as static methods cannot be overridden.
If you want to maintain the state of the object, you have to go with the singleton instead of static methods.When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.
You can have a detailed description here
Read more: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html#ixzz2iNE3rW4i
For me: Singleton is an anti-pattern and should only be used if there is a strong reason, also a class only holing public static variables is not acceptable in my opinion, this sound not realy object orientated to me. You could use Dependency Injection, the benefits are testability and you can avoid the doublecheck on creating a singleton (if you don't use an enum).
this would look like:
public class SharedObject{
// content
}
public class Worker{
private final SharedObject sharedObject;
public Worker(SharedObject sharedObject){
this.sharedObject = sharedObject;
}
}
With this way you also see, where the objects come from, you can easyly mock the shared object using Mocktio. It forces you to structure your code for easy testing, meanwhile it will go in a more modular direction.
I prefer static methods for classes which are stateless, just like Math or System class, and singleton as vice versa->for statefull classes, like FacesContext.
An all-static class is often used for shared utility methods that are grouped logically together but do not share state (fields) between them.
A singleton is better if:
You might want different objects with different behaviors to play that role.
The object needs to implement an interface (e.g. a shared ActionListener)
(Another way of saying this: If you need polymorphism, your singleton must be an object and not a class)
It is preferable not-heritable and non-instantiable class with static methods. e.g.:
public final class Constants {
private Constants() {
// non-public constructor
}
public static final Pattern ID_PATTERN = Pattern.compile("^\\d{4,10}$");
public static final Locale DEFAULT_LOCALE = new Locale("en", "US");
...
}
Use singleton only if you want to maintain some state, similar to the application scope. However, must be two classes if you want a clean design.