Static methods in abstract class? [closed] - java

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
I recently learned from a video that it's a good practice to turn a Java class into abstract if all of its methods are static for performance reasons.
Can anyone explain why this is the case?

This is likely to prevent people from creating instances of the class. Java code is expected to create lots of objects that are useful for a short time and get garbage-collected, so it is hard to say this is any kind of substantial performance win. It seems more like a way to communicate the intention behind a class.
Another alternative is, instead of making the class abstract, make the class final. This is the approach taken in JDK code, for instance, java.lang.Math:
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
With either of these approaches you should give the class a private constructor. That prevents anyone from instantiating it and makes it clear the class's purpose is to provide a home for the static methods. The downside here is code coverage tools tend to report the constructor as uncovered.
A third alternative, as of Java 8, is to put the static methods on an interface. Any methods with an implementation that aren't default get assumed to be static methods. The advantage of that approach is there is no constructor to make private, and the code coverage tools will be happy.
With an abstract class (but without the private constructor), or an interface, there is also the possibility of extending or implementing the type to make all the static methods available without static imports. See this link for an example. With the java.lang.Math approach that isn't an option.

You don't have to make it an abstract if it has static methods. if you make it an abstract class then no one can instantiate this class.
on the other hand, you can declare a class with a private constructor, so no one, not even a subclass, can instantiate an instance of your class.
public class A
{
private A()
{
throw new RuntimeException("Instantiation of MyUtility is not
allowed!");
}
public static void aMethod()
{
// Your method here.
}
}

Related

Is it a good practice to declare class with only static members as abstract? [duplicate]

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 3 years ago.
Improve this question
I recently came across some code where a public static method was defined inside an abstract class. I am wondering whether this is considered good practice or an anti-pattern?
I've produced a simple example program to illustrate what I mean.
public abstract class StaticMethodsInAbstractClassesStudy {
public static int adder(int a, int b){
return a + b;
}
}
public class StaticMethodsInClassesStudy {
public static void main(String [] args){
System.out.println(StaticMethodsInAbstractClassesStudy.adder(2, 3));
}
}
When you run the code you get the result of 5 which proves that I was able to run code inside of an abstract class.
I've deliberately not added extends to StaticMethodsInClassesStudy to emphasise the point that it's perfectly possible to run code directly inside an abstract class without instantiating an extending class.
Personally I would have thought that this is bad practice since you're using an abstract class as a normal Class and thereby bypassing the intent of abstract classes. Shouldn't these kinds of methods be kept in separate "normal" java classes e.g. utility classes ?
It's not bad practice per se, unless the abstract class is actually not meant to be subclassed, and abstract is only there to prevent instantiation. The best practice for a class providing only static utilities would be to make it final, and to have a private constructor.
I agree with you that a abstract class make us think of something to not use until it will be instantiated.
It's allowed and useful to insert some support methods inside an abstract class without enforce the developer to implement that class.
Also in an Interface you can put static methods, and you can use them without implementing that interface.

Is exposing static methods in abstract classes considered good or bad practice [closed]

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 3 years ago.
Improve this question
I recently came across some code where a public static method was defined inside an abstract class. I am wondering whether this is considered good practice or an anti-pattern?
I've produced a simple example program to illustrate what I mean.
public abstract class StaticMethodsInAbstractClassesStudy {
public static int adder(int a, int b){
return a + b;
}
}
public class StaticMethodsInClassesStudy {
public static void main(String [] args){
System.out.println(StaticMethodsInAbstractClassesStudy.adder(2, 3));
}
}
When you run the code you get the result of 5 which proves that I was able to run code inside of an abstract class.
I've deliberately not added extends to StaticMethodsInClassesStudy to emphasise the point that it's perfectly possible to run code directly inside an abstract class without instantiating an extending class.
Personally I would have thought that this is bad practice since you're using an abstract class as a normal Class and thereby bypassing the intent of abstract classes. Shouldn't these kinds of methods be kept in separate "normal" java classes e.g. utility classes ?
It's not bad practice per se, unless the abstract class is actually not meant to be subclassed, and abstract is only there to prevent instantiation. The best practice for a class providing only static utilities would be to make it final, and to have a private constructor.
I agree with you that a abstract class make us think of something to not use until it will be instantiated.
It's allowed and useful to insert some support methods inside an abstract class without enforce the developer to implement that class.
Also in an Interface you can put static methods, and you can use them without implementing that interface.

Why would anyone define a static method in an interface in java 1.8? [closed]

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
Why would any one define a static method in an interface in JAVA 1.8?
I need to know the different examples/usecases/requirements where static method would come handy.
How can a static method in an interface would be beneficial for a developer?
There are many use cases for static methods in interfaces. The most common by far, though, is factory methods that have made it easy to create instances of their respective interfaces.
Consider these examples:
Comparator.comparing
List.of
Set.of
Stream.of, Stream.generate
Without these factory methods in interfaces, there would be too many constructor calls in disparate implementation classes.
Some of these examples were only added with version 9 of Java, but the feature opened many possibilities.
These static methods are also used for different purposes. It's now possible to have a method like Collections.sort implemented in the right place, Collection.sort, thus avoiding unnecessary extra classes.
Most commonly, factory and utility classes.
In addition to the factory examples in the other answer, consider the Collections class - this has been in the JDK for over a decade, but would never have been needed if the static methods could just have been defined on the Collection interface from day 1.
Here I found nice explanation why we have static methods in interfaces:
http://www.baeldung.com/java-static-default-methods
The idea behind static interface methods is to provide a simple
mechanism that allows us to increase the degree of cohesion of a
design by putting together related methods in one single place without
having to create an object.
Pretty much the same can be done with abstract classes. The main
difference lies in the fact that abstract classes can have
constructors, state, and behavior.
Furthermore, static methods in interfaces make possible to group
related utility methods, without having to create artificial utility
classes that are simply placeholders for static methods.
So yes, the one of the examples is that instead of creating utility classes for some behavior, calculation related to your interface, you can choose to define related static methods directly in the interface. So you group functionality on the right place. You avoid additional classes
public interface Vehicle {
static int getHorsePower(int rpm, int torque) {
return (rpm * torque) / 5252;
}
}
Vehicle.getHorsePower(2500, 480));
public interface Cube {
static double volume(double a){
return a * a * a;
}
static double surface(double a){
return 6*a*a;
}
}

Static methods added in interfaces in java 1.8 [closed]

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 8 years ago.
Improve this question
As we know that in java 1.8 static methods are allowed in interfaces , I have seen some answers like static methods defined in interface from jdk 1 8 why did they need to do so
but I am not satisfied. Furthermore I think it may cause problems like :
public interface MyInterface{
public static void myMethod();
}
class MyClass{
MyInterface.myMethod(); // since myMethod is static but a huge error is waiting for us here ?
}
But I still think there is a way out of this since this is added by professionals , so can anyone please explain how oracle solves this issue and what is the need to add this ?
Thank you in adavance.
I have not used java 1.8 so I never knew that static methods in java needs to be defined not just declared , I always thought of the Interfaces as a Pure Abstract Class I think that's why the idea of defining a method seemed strange to me . Thank you for your help ! .
Talking about "what is the need to add" static methods:
Quoting from http://www.informit.com/articles/article.aspx?p=2191423
Before Java 8 made it possible to declare static methods in
interfaces, it was common practice to place these methods in companion
utility classes. For example, the java.util.Collections class is a
companion to the java.util.Collection interface, and declares static
methods that would be more appropriate in the relevant Java
Collections Framework interfaces. You no longer need to provide your
own companion utility classes. Instead, you can place static methods
in the appropriate interfaces, which is a good habit to cultivate.
Also static methods in interfaces are good for providing utility methods like null check, collection sorting etc. And importantly it provides security by denying implementation classes from overriding it.
There's no problem here, the static method is owned by class, not it's members, so the only error here is the fact you didn't defined the method itselt (just declared it, which is not allowed with static methods).

Is this appropriate to create a class with one method? [closed]

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 9 years ago.
Improve this question
I'm wondering whether it's a good practice to produce the code which being used like this:
new TemplateProcessor(inputStream).processTemplate("output-path.xhtml");
Here, TemplateProcessor contains only one public method. It seems the code above can be expressed with a static method, but I would like to avoid that. The reason is simple: object may contain encapsulated state, (maybe now, maybe in the future). Dear experts what would You prefer in this case?
It's reasonable to encapsulate the code in a static method, with static imports it becomes very easy to use:
processTemplate(inputStream, "output-path.xhtml");
The above static method would just be a façade, a convenience method to be used for that specific use case that your class is solving, supposedly one that's very common. It does not prevent the class from evolving, even adding state. For more specialized use cases, the consumers can still create instances of the class and use its methods as usual.
To make that separation even more pronounced, you could add the static method to a sibling class, like TemplateProcessorFacade, which is a non-instantiatable utility class:
public final class TemplateProcessorFacade {
private TemplateProcessorFacade() {}
public static void processTemplate(...) {
...
}
}
A class should be seen as an object or module that performs a key role or function in the program. A role that no other class or module fulfils. For example, you can have a class Animal that provides the functions sleep(), run() . But you might want a class for carnivores which also kill() , hunt() etc. So you implement the Carnivores class by extending from Animal, which does what all variables of type Animal do, but also additionally kill and hunt.
If your class has only one public method, but if it's important for the design to have it as a separate module, then having a class for it is good. You can extend it later, if needed.
Also you can, keep the sleep() and run() functions static and public, all Animal's do that, and so you can just do Animal.sleep() and such, without creating a separate instance. But a function like roar() shouldn't be.
Update:
The reason I said, sleep() and run() can be static is, there can be a class Man who also sleeps and runs.
The question to ask:
Does it make sense to call sleep() and run() or any function of a class without initializing an object of that class? If yes, then it makes sense to make it static.

Categories

Resources