Using static field in generic singleton [duplicate] - java

This question already has answers here:
Static method in a generic class?
(12 answers)
Closed 5 years ago.
Thank you all for reading, i'm trying to understand Generics, and i got this excersice where i create a singleton with a generic parameter.
public class Singleton<T> {
public static T getInstance() {
if (instance == null)
instance = new Singleton<T>();
return instance;
}
private static T instance = null;
}
But i got this error: Cannot make a static reference to the non-static type T
What can i use as a workaround? Or better yet, what causes the error?

Look at newaccts answer to this post:
You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.

Related

Understanding static and instance members [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 2 years ago.
I've learned that I should use Object(instance) for using instance field in static method.
For example:
INSTANCE FIELD(==speed)
that is declared in public class Car, should be used through Object in static method (ex. 'public static void main(String[] args) )
like this.
Car myCar = new Car();
myCar.speed = 60;
So, the reason I should use object is because static method is located in CLASS and for being shared to objects, but on the other hand, instance field is just Frame that is not substance?
For using this instance field in static method, do I have to make the instance that is called 'object'?
In other words, is this process right?:
instance field -> OBJECT( substantialization) -> static method.
I'm wondering what I understood
static methods are used for 3 reasons:
"stateless" methods. A good example of this would be Math.sin
Global "singletons": singleton is in quotes because the singleton pattern is not used everywhere in java. An example of where it is could be Runtime.getRuntime() an example of where it isn't might be Thread.getUncaughtExceptionHandler (implicit singleton)
Program entry point (public static void main) : It makes sense for a program to start outside of an object context (rather than innside)

Can you use the class for calling method? [duplicate]

This question already has answers here:
Difference between Static methods and Instance methods
(10 answers)
Closed 4 years ago.
Whenever I have to call a method from another class, I first create an object and then call it through the object. But while I was writing some code, I mistakenly wrote classname.methodname(); and it worked.
I would usually write,
classname obj = new classname();
obj.methodname();
Here is the actual code:
Class 1
public class Dataset {
public static List<ECCardData> getDataset() {
//Code
}
in Class 2
List<ECCardData> dataset = Dataset.getDataset();
I noticed that the methodname() was static. Was that the reason?
Yes, for static methods (with suitable access modifier) you can call directly with your class by
YourClass.yourMethod();
and this way, too
YourClass anObject = new YourClass();
anObject.yourMethod();
Happy coding.
I hate answering my question, but I found the correct answer.
When a method is declare static, only one instance of that method will exist. When you create an object a new instance of the method is created, which is not possible for a static method. Therefore you use the class name.
classname.methodname(); //only one instance
classname obj;
obj.methodname(); //instance with obj as Object(IDE gives warning, should not be allowed, ideally)
The basic paradigm in Java is that you write classes, and that those
classes are instantiated. Instantiated objects (an instance of a
class) have attributes associated with them (member variables) that
affect their behavior; when the instance has its method executed it
will refer to these variables.
However, all objects of a particular type might have behavior that is
not dependent at all on member variables; these methods are best made
static. By being static, no instance of the class is required to run
the method.
You can do this to execute a static method:
classname.staticMethod();//Simply refers to the class's static code But
> to execute a non-static method, you must do this:
>
> classname obj = new classname();//Create an instance
> obj.nonstaticMethod();//Refer to the instance's class's code

Why instance method cannot override the static method [duplicate]

This question already has answers here:
Why doesn't Java allow overriding of static methods?
(22 answers)
Closed 5 years ago.
class Abc{
public static void hello(){
System.out.println("parent");//Line1
}
}
class Abc1 extends Abc{
public void hello(){//Line2
System.out.println("child");//Line3
}
}
Compiler gives error at line 3 saying that
This instance method cannot override the static method from Abc
Why can static methods not be overridden by a instance method?
Simple: because the language specification says so.
That is one of the downsides of static methods: there is no polymorphism for them! Conceptually, they are not meant to be overridden. That is all there is to this.
To be precise: the JLS says differentiates between static and non-static method and states:
An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

Why make singleton object private instead of public [duplicate]

This question already has answers here:
singleton public static final
(5 answers)
Closed 7 years ago.
In Java you can create a singleton like this:
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
}
Is there any reason why you just couldn't make instance public and dispense with getInstance?
The modern (since Java 1.5 I think) canonical way to create singletons in Java, shamlessly copied from this answer, which has a lot more background and larger example, is this, which replaces the code in your question:
public enum SingleObject {
INSTANCE;
}
To answer your question directly: you are asking a wrong question, and the answer is, it shouldn't be either of the alternatives you give.
In Effective Java, Joshua Bloch says on the static factory method advantage over the public final field is:
One advantage of the factory-method approach is that it gives you the flexibility
to change your mind about whether the class should be a singleton without
changing its API. The factory method returns the sole instance but could easily be
modified to return, say, a unique instance for each thread that invokes it.
And he also says:
A second advantage, concerning generic types, is discussed in Item 27. Often neither of these advantages is relevant, and the final-field approach is simpler.
Otherwise in Java he writes that "a single-element enum type is the best way to implement a singleton":
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

Why ClassName.class.getFields() returns only public fields? [duplicate]

This question already has answers here:
this.getClass().getFields().length; always returns 0 [duplicate]
(3 answers)
Closed 7 years ago.
I have one class A
public class A {
String host = "localhost";
public String port = "8078";
protected String preFix = "www.";
private String postFix = "/uploads";
}
I am getting field details of class A using below code
public static void main(String[] args) {
Field[] fields = A.class.getFields();
System.out.println("fields are:" + Arrays.toString(fields));
}
The output is
fields are:[public java.lang.String org.test.A.port]
I understand getFields() method returns only those fields which are declared with public access specifier.
But why Java implemented getFields()
like this?
What is the main intention of Java Team for this kind of implementation?
There are two methods in the Class class concerning the fields:
getFields() returns all the publicly accessible fields of this
class (interface) and all of its superclasses,
getDeclaredFields() returns
all fields that are declared on this class (interface), including fields with
public, default, protected and private visibility.
The distinction between those two methods use cases should be quite clear.
Purpose of getFields is to return all public fields available via class, including inherited ones.
If you are looking for list of fields declared in this class use getDeclaredFields.
Since there is getDeclaredFields which returns fields regardless of its modifier your question does not make sense. The point was to have methods for all use cases which are common. For example using getFields you can iterate over a static class having constants only (this was before enums were introduced). So to answer your question this was partly to cover common use cases and now partly legacy.

Categories