What exactly mean declare a Java class as MyClassName<Param>? [duplicate] - java

This question already has answers here:
What is Type<Type> called?
(3 answers)
Closed 7 years ago.
I am working on a Java application in which I found this class:
public class TipologiaGenerica<K> {
private K codice;
private String descrizione;
public TipologiaGenerica(K codice, String descrizione) {
this.codice = codice;
this.descrizione = descrizione;
}
public K getCodice() {
return codice;
}
public void setCodice(K codice) {
this.codice = codice;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
}
As you can see this class is declared as: TipologiaGenerica and K seems to be something like an object type that could be passed when a specific TipologiaGenerica object is created and that determinate the type of one of its inner field, this one:
private K codice;
Infact, somewhere else in the code, I find a TipologiaGenerica object creation:
TipologiaGenerica<String> dataPerLista = new TipologiaGenerica<String>(dataString, dataString);
What exatly mean? I think that doing in this way it is creating a specific TipologiaGenerica object having the inner codice field that is a String.
Is it my reasoning correct? What is the name of this specific use of Java? What are the most common purpose of this type of constructor?

It is called Generic Types. You can use them to generalize some classes / methods into typesafe code "templates".
Check the Oracle's tutorial regarding this topic
https://docs.oracle.com/javase/tutorial/java/generics/

Is it my reasoning correct?
yes.
What is the name of this specific use of Java?
Generics
What are the most common purpose of this type of constructor?
type safety

This is called generics in Java. The use of this type of programming is to ensure type safety and that you could reuse the same parent class by inserting various object types. for e.g. in your case, you have made
TipologiaGenerica<String>
Users can reuse the same class for other types, for e.g.
TipologiaGenerica<Integer>

Related

Issue with type parameter: "cannot select from parameterized type"

I am facing an issue with generics.
Here is one of my classes that uses generics:
public class TokenServerResponse<D> {
private String responseCode;
private String responseMessage;
private D responseData;
....
Here our class: TokenServerResponse is parameterized with D.
I would like to specify the type in one of our methods as follows:
protected ResponseEntity<TokenServerResponse<DigestResponseData>> digest(long globalMerchantUId, String expirydate, String pan, boolean updateExpiryDate) throws Exception {
DigestRequest digestRequest = new DigestRequest();
digestRequest.setGlobalMerchantUid(globalMerchantUId);
digestRequest.setExpiryDate(expirydate);
digestRequest.setPan(pan);
digestRequest.setUpdateExpiryDate(updateExpiryDate);
return restTemplate.postForEntity("/digest", digestRequest, TokenServerResponse<DigestResponseData>.class);
}
However, I get the following compiler error: cannot select from parameterized type.
How can I use the type parameter D? I have also tried casting to no avail. What am I getting wrong?
Here is how the digest method is called:
ResponseEntity<TokenServerResponse<DigestResponseData>> digestResponseEntity = digest(823, "1505", pan, true);
Here :
return restTemplate.postForEntity("/digest", digestRequest, TokenServerResponse<DigestResponseData>.class);
If your method expects to have a class value as last argument, you can only provide a class for it. Providing a class with generic type is not possible.
Casting is unavoidable but if you change your TokenServerResponse class to use also inheritance.
public abstract class TokenServerResponse<T> {
private String responseCode;
private String responseMessage;
private T responseData;
public T getResponseData() {
return responseData;
}
}
public class TokenServerResponseDigestResponseData extends TokenServerResponse<DigestResponseData> {
}
Now you can use TokenServerResponseDigestResponseData class here :
return restTemplate.postForEntity("/digest", digestRequest, TokenServerResponseDigestResponseData.class);
And when you do :
TokenServerResponseDigestResponseData instance = ...
DigestResponseData data = instance.getResponseData();
you don't need any cast.
Of course this solution is interesting if you have not dozen of classes to make them inherited from the TokenServerResponse class and you would like to work with specific types in client code.
In your case, DigestResponseData is required to make your processing since your generic type doesn't rely on a specific type but on Object type, so you should cast at a time in this way : TokenServerResponse to TokenServerResponse<DigestResponseData>.
With the proposed solution, it is not required any longer.

How to create different objects depending on the parameter passed? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I have a use-case like this:
Based on the parameter passed - I have to create an object corresponding to it but the underlying functionality remains same.
public void selectType ()
{
String type = "ABC";
publishType(type);
}
public void publishType(String type)
{
if (type.equals("ABC"))
ABCtype publishObject = new ABCtype();
if (type.equals("XYZ"))
XYZtype publishObject = new XYZtype();
publishObject.setfunctionality();
}
What is a better way to approach this?
Which design pattern does it fall in?
Another doubt I have is - how to initialize publishObject?
It gives an error like this.
but the underlying functionality remains same
you maybe consider design suing interfaces..
Do some nice Archi- Design like:
define an interface, and 2 classes that implement the interface, then
declare an object foo and initialize it according to the parameter..
Example:
interface IObject{
//methods here
}
class A implements IObject{}
class B implements IObject{}
public void selectType ()
{
IObject foo = getObject(1);
}
public IObject getObject(int type){
if (type ==1){
return new A();
}else{
return new B();
}
}

How to create a "Setter" in Java [duplicate]

This question already has answers here:
Set and Get Methods in java?
(16 answers)
Closed 7 years ago.
I am unsure how to create a setter method in java.
Everything that I found on the internet either shows how to "generate" one in eclipse or doesn't include what I am looking for.
I am looking for a simple answer in plain terms, if that is possible.
I understand what a setter-method does, but am unsure about the syntax and specific code.
Thank you for your time.
I'm assuming you mean a setter method as in set an object?
private String yourString;
public void setYourString(String yourString) {
this.yourString = yourString;
}
This is basic code though so you probably mean something else?
Let me know.
A setter is a method which sets a value for one of your parameters. E.g. many people say it's not nice to have a public variable in a class:
public class SomeClass {
public int someInt = 0;
}
now you can access the variable someInt directly:
SomeClass foo = new SomeClass();
foo.someInt = 13;
You should rather do something like that:
public class SomeClass {
private int someInt = 0;
// Getter
public int getSomeInt() {
return someInt;
}
// Setter
public void setSomeInt(int someIntNew) {
someInt = someIntNew;
}
}
and access it through:
SomeClass foo = new SomeClass();
foo.setSomeInt(13);
All this is just convention... You could name your setter-method however you want! But getters and setters are a good (and readable) way to define access to your class varaibles as you like it (if you want to make it read-only you could just write the getter, if you don't wan't anybody to read the value you could only write the setter, you could make them protected, etc...)
A small code for getter and setter
public class Test {
String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
Advantage of setter is that a setter can do sanity checks and throw IllegalArgumentException.

How can I use a non-static (dynamic instance) object as return for a static method in Java? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have searched through stackoverflow as well as a few other sites and sadly have not found this question asked, let alone answered. Maybe my approach is best attempted another way? I am new to Java; this should be a really easy answer I would think.
The issue:
I have a static method that I would like to return values from. For convenience and neatness I would like to use my own class instead of an ArrayList, String[], or similar. Problem is that I cannot instantiate my class within the static method (as I expected could be an issue). Funny thing though: using String[] or Object as the return does work (which is an instance of those classes)... so why can't I use my own class instance?
Example:
public static String[] decodeText(String codeString) {
//Parse codestring and return values (not included in this example)
String[] data = new String[3];
data[0]="This";
data[1]="does";
data[2]="work";
return data;
}
The above works great but when I use my own class to return values the compiler gives me the "non-static variable this cannot be referenced from a static context" (NOTE: edited to show that these classes are nested within the JInputs class which apparently is necessary to reproduce the error):
public class JInputs extends JOptionPane {
//A lot of missing code here (which shouldn't be necessary to reproduce issue)
public class UserData {
public String userName;
public String code;
public long milliTime;
UserData() {
}
UserData(String userName, String code, long milliTime) {
this.userName = userName;
this.milliTime = milliTime;
this.code = code;
}
}
public static UserData decodeText(String codeString) {
//Parse codestring and return values (not included in this example)
UserData data = new UserData();
data.milliTime = System.currentTimeMillis();
data.code = "blah";
data.userName = "Me";
return data;
}
}
Obviously, I could make my UserData class a static class but then wouldn't subsequent calls to the method change the values of the original call? How do Java programmers return neat data from static methods? Why does it allow built-in classes to be instantiated but not user defined classes?
The only problem this code has is a misplaced curly bracket:
public class UserData {
public String userName;
public String code;
public long milliTime;
UserData() {
}
UserData(String userName, String code, long milliTime) {
this.userName = userName;
this.milliTime = milliTime;
this.code = code;
}
} //end of class!
//this method is outside the class!
public static UserData decodeText(String codeString) {
//Parse codestring and return values (not included in this example)
UserData data = new UserData();
data.milliTime = System.currentTimeMillis();
data.code = "blah";
data.userName = "Me";
return data;
}
I imagine what you want instead is this:
public class UserData {
public String userName;
public String code;
public long milliTime;
UserData() {
}
UserData(String userName, String code, long milliTime) {
this.userName = userName;
this.milliTime = milliTime;
this.code = code;
}
public static UserData decodeText(String codeString) {
//Parse codestring and return values (not included in this example)
UserData data = new UserData();
data.milliTime = System.currentTimeMillis();
data.code = "blah";
data.userName = "Me";
return data;
}
}
The above works great but when I use my own class to return values the compiler gives me the "non-static variable this cannot be referenced from a static context"
The code you posted does not result in that error. You either copied the code wrong, or you're looking at an old error.
Obviously, I could make my UserData class a static class but then wouldn't subsequent calls to the method change the values of the original call?
There really isn't a concept of "static class" the way you're describing. A static class is simply an inner class that can be accessed without an instance of the outer class. All of its members still act like the members of a normal class.
How do Java programmers return neat data from static methods? Why does it allow built-in classes to be instantiated but not user defined classes?
What you posted would work fine. Java does not make a distinction between "built-in" classes and "user-defined" classes.
Looking at the error you have, your question probably misses a bit of code, it is probably like:
public class SomeClass {
public class UserData {
....
}
public static UserData decodeText(String codeString) {
UserData data = new UserData();
....
}
}
Inner Classes
So you are using the concept of Inner Classes. Those classes need to have access to an instance of their parent class to be created (here UserData would need to have access to an instance of SomeClass). This access is provided by the JVM when the inner class is created from within a non-static method via the "this" pointer. However, one does not have access to "this" in a static method: this is what the compiler is telling you: UserData cannot be created because it needs to have access to this ("non-static variable this cannot be referenced from a static context").
But you could create a new instance of UserData in any non-static method of SomeClass or UserData and any of their subclasses.
Your Use Case
In your case, you do not seem to need an inner class. You only need a nested class when you want to have access to the members of the parent class. Otherwise a static nested class is enough.
Your Question
I could make my UserData class a static class but then wouldn't subsequent calls to the method change the values of the original call?
No the subsequent callq to the method wouldn't change the value of instances created by previous call to the method. A static class does not mean that its variables are static, or that it is a singleton. A static class is basically like a standard class, only it is nested within another classes definition.
For more information on the difference between static and non-static nested classes see the Oracle documentation on this.

how to get enum on the basis of value? [duplicate]

This question already has answers here:
Getting enum associated with int value
(8 answers)
Closed 7 years ago.
i have a enum
public enum Category {
NonResidential("Non-Residential"), Residential("Residential");
private String category;
BuildingAssetCategory(String s) {
category = s;
}
public String getType() {
return category;
}
public void setType(String type) {
this.category = type;
}
}
I want to get the enum on the basis of value its having.
i have String of value Non-Residential, then how can i get the enum returning `NonResidential.
P.S i to want to create own magic rather then something java supports.
i have read out many question like this but i want different ans.
There is no magic here, since it's your own define field ('category') you should write your own static method to search by it. For example:
public enum Category {
...
public static Category findByName(String cat){
// loop over Category.values() and find the requested cat
}
btw ValueOf will work if you provide the enum name (e.g. "NonResidential") but it won't work for category name (e.g. "non-residential")
Use valueOf.
Category.valueOf("Non-Residential");
This will return you the enum.

Categories

Resources