Scenarios where static java methods can be used? [duplicate] - java

This question already has answers here:
In what situations is static method a good practice?
(11 answers)
Closed 9 years ago.
what exactly is the use of java static methods? Yes i understand that they can be called without creating instance if in the same class. They can be called directly.
In case of main method, as it will be the first method to be called and has to be called without initializing it, static word justifies.
But in which other scenarios do we need to make a method static?

Simply
If your method not related/depend on any of the instances they can better be static methods.
You points are on top and moreover,To avoid unnecessary object creation
An example from the java API is Math, all the variables and methods are static. Does it make sense to have to create a Math object just to call a single method.
Often people use this to write some Utility methods.

You gave the answer in your question: static methods are useful whenever you don't need an instance to do something. The typical example is:
public static int min(int a, int b);
This method just gives the min of two numbers and does not need a context (instance) to work.
Now you can use it as:
int min = YourClass.min(1, 2);
Had you declared it as an instance method, you would need to unnecessarily create a YourClass object.

Static methods are used when you don't want to make an object of a class, such as in the Math class. If the math methods are static you don't have to create an object of the Math class. Other uses include for universal counter variables(making them static) and variables that everyone should know but are themselves are unable to be edited. Some more advanced uses include in threading and design patterns.

Related

Ensure that a static method is implemented [duplicate]

This question already has answers here:
Alternatives to static methods on interfaces for enforcing consistency
(7 answers)
Closed 8 years ago.
I have several Java classes which contain static methods. I want to ensure that these static methods are implemented by each of the classes. How can I enforce that, since declaring static methods is not allowed in interfaces in Java?
If you have code that calls these methods, it won't pass compilation if they are not implemented. If you don't, you don't really need them.
Sort answer: You can't enforce that.
Static methods are not inherited the same way as instance methods, so you wouldn't be able to use it for anything meaningful anyway: You can't call MySuperClass.staticMethod() and expect some subclass to handle the call. This means that you have to call it using MySubClass.staticMethod() in which case you'll get a compilation error if MySubClass doesn't implement staticMethod.
I would suggest you look into solving it using a singleton or factory pattern and use instance methods:
MySuperClass.getInstance(parameter).yourMethod()
static methods are allowed on interfaces in Java8.
However, there's no way to enforce a class to implement a static method.
The only thing you can do, is make them non-static and abstract (either in an interface or in an abstract class).

Create an instance for the class Scanner, but not for Math class in java?

Why do I have to create an instance for the class Scanner, but not for Math class in java?
I hope you guys can explain me this with good examples.
I understand it in this way:
We are asking the same in Math.pow() for examples.
It will always be the power of a number.. (x,y) for example or (x,2)
But .print() or .println() will change the value .. ? That's why we need to create an instance for the class Scanner.. am I right?
Edit: I do know it is static, but I need a more explained in detail answer then.. "its just the way it is"..
Math defines only static methods because it doesn't contain internal states.
You could argue:
But what about polymorphism, what if I want to override Math class?
=> classic mathematical operations are unlikely to be overridden for most of 99% of programs.
So it acts as a simple utility class, waiting for inputs, and outputting some result in one call.
See as an example Math#max:
public static double max(double a, double b)
Since it's static, it means that it's not associated with any object. You can simply call it.
Now look at PrintStream#println:
public void println(boolean x)
Since it's not static, you cannot directly call it by writing PrintStream.println(something).
Think about it, it really make sense that max is static since it doesn't have to be associated with an object, it doesn't really needs an information about an object as it doesn't care about it. It has a well defined behavior for all objects. No special treatment for some objects over others.
Because you are acessing static methods of Math. Note you are using "class i.e. Math".method.
While for Scanner, you use instance as all the methods like nextInt, next are defined as non static.
The constructor for Math is private, meaning you cannot call it from outside Math.
The reason is that it is a class holding a bunch of static utility methods, and there is no need to ever generate an instance of it.
The methods on the Math class are static methods, whereas the ones for the Scanner class are not.
The Scanner class isn't using static methods because each instance needs to maintain their own state, different from other instances of Scanner.
The Math class are simple utility functions that have no state, so they can be static.

What exactly are and when are static methods/variables used? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 8 years ago.
I'm quite new to Java and I'm trying to understand static variables and methods. Could someone give me a brief explanation of why I'd use the static method over the instance method and also what would be the ideal situation to use static variables? I know that static variables and methods are part of the class and not an instance of said class but I'm having trouble understanding when I'd use it.
Thanks!
These are the main differences
1.Static variables take memory only 1 time during the lifetime of program.
2.You can call static variables or methods. without creating the object of that class by classname only.
3.Static variables can be called in static and non-static context.
Mainly static variables are used to save memory because every object takes memory .
Static members relate to a type not a concrete instance. So instance methods and variables concern the identity of the instance, e.g. an instance method can alter the state of the object.
To some extend this is a religious question. Some people prefer to create static methods in a class when they do not access any instance variable. Other people do not like this approach. Another usual usage is creating factory methods, able to create an instance of an object while itself being called statically.
Often there are utility classes that contain static methods to serve clients with some functionality that is not bound to any type context. But all too often these utility classes get abused by using them as a trash bin for all sorts of methods a programmer did not find a fitting class for. This may be a result of poor design.
A popular use of static variables is the definition of an logger instance (e.g. SLF4J) for a class because loggers are thread safe and can be used by all instances and static methods alike. One advantage is (see a comparison) that only one instance has to be created for all instances of the containing class.
For static variable or method, you can think of that there is only one copy of the variable or method during the whole life time of the program.
So if you there is variable whose value should be shared across all the processes or thread, you can declare a static variable. For example, when you want to use a singleton pattern, you will need a static variable to indicate if there is instance of the class already.
For static methods, I would use them when state of the class is not important. I think the best example is java.lang.Math, they are all static methods, and returns the expected values to you no matter what you called before.

I need to use a method in two classes. which approach is a good practice? making a method public vs making it static vs making a duplicate

I have two adapter classes that are in the same package where I need the following method..
private int getAlphaValue(int backgroundTransparency) {
int backgroundOpaquePercentage = 100 - backgroundTransparency;
int alpha= (255 * backgroundOpaquePercentage) / 100;
return alpha;
}
Have a copy of this method in each of the classes and make them private.
Have the method in one of the classed and make it static and protected to be able to use in both methods
Which of the above two approaches is a good practice and an efficient one?
Create a new GraphicsUtil class and add such utilitarian methods as static there. Such util methods do not belong to any one class and make more sense to be made available globally to the application through a static/global context.
All other graphics classes would then use it as
int alpha = GraphicsUtil.getAlphaValue(50);
No copying ever! That's why we use Object-oriented programming nowadays, to avoid code duplication.
Just make this method public/protected.
You shoud give more information about the two classes.
Looking at the method, it should become static, because it does not use instance variables.
So you don't have to keep it duplicate.
step 1 : create a third class
step 2 : write that method
step 3 : in your classes call that method with object reference of your newly created class
The first approach is an anti-pattern. If you have a bug in your method, you will have to fix it twice.
The second approach is better, but I would go for a 3rd approach:
Have your 2 classes inherit from the same base class, and have the method in that class. No need to make it protected!

Can we override static method in Java? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why can’t static methods be abstract in Java
Static methods and their overriding
Why doesn’t Java allow overriding of static methods ?
Can we override static method in Java?
No. Static methods are tied to the class they're defined in. They're invoked through the class, not through an object, and there is no dynamic dispatch where overriding could happen.
You're probably confused because Java allows you to invoke static methods through an object reference. That's generally considered a design error, and it does not work like invoking instance methods, because the compile-time type of the reference decides which method gets invoked.
No, but you can shadow it.

Categories

Resources