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();
}
}
Related
This question already has answers here:
Can I add and remove elements of enumeration at runtime in Java
(7 answers)
Closed 6 years ago.
Suppose I have an Enum like this:
public enum BlaEnum{
BLA1,
BLA2;
private static final String BLA_ONE = "bla one";
private static final String BLA_TWO = "bla two";
public static String getName(BlaEnum bla) {
switch(bla) {
case BLA1: return BLA_ONE;
case BLA2: return BLA_TWO;
default: return null;
}
}
public static BlaEnum getBla(String bla) {
switch(naam) {
case BLA_ONE: return BLA1;
case BLA_TWO: return BLA2;
default: //return new enum value via reflection;
}
}
}
How can I, depending on the incoming String, return a new Enum value at runtime?
As if there would be an extra value declared:
public enum BlaEnum {
BLA1, BLA2, EXTRA_BLA
...
}
You can't. Enums are constant.
If you've run into a case in which you need to return a new enum value at runtime, then you should seriously rethink your design. What you probably need is is an actual class, or maybe some catchall enum value like "other".
You can't do this with an enum. As it says in JLS Sec 8.9:
An enum type has no instances other than those defined by its enum constants.
However, you can define an interface:
interface SomeInterface {
// Add methods as required.
}
And have your enum implement this interface:
enum BlaEnum implements SomeInterface {
BLA1, BLA2;
}
As well as a concrete class implementing the interface:
class SomeInterfaceImpl implements SomeInterface {
// ... whatever body
}
And have your getBla(String) method create an instance of SomeInterfaceImpl I N the default case, e.g.
default:
return new SomeInterfaceImpl(bla);
(Obviously, the return type would need to be SomeInterface, rather than BlaEnum).
You might also want to use some sort of memoization if you want the same instance of SomeInterfaceImpl to be returned if the method is invoked multiple times with the same parameter.
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>
This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
As far as I know this is used in following situations:
this keyword is used when we want to refer to instance variable having same name as local variable.
Calling one constructor to other in same class.
Pass the class instance as an argument to the method.
Accessing the outer class variables.
But I have gone through my project code where they are using this in getters like:
class a {
int time;
int getValue() {
return this.time * 5.;
}
}
As far as I know, every object has its own copy of instance variables and methods, so will returning this way makes any sense.
Please clarify.
Stackoverfow problem referred:When should I use "this" in a class?
Many people (I'm one of them) use this keywords even when it is not explicitely needed.
Some people find it more clear to put this in front of anything which belong in the same class, the same logic apply to super.
Some people always use this by reflex for a better auto-completion (pop-up appear automatically, lazy programmer) in some IDE.
These points are mostly opinion based and doesn't really matter.
For the other uses, as you mentionned, it can be used to pass parameter to another constructor, pass the class instance or to distinct when you have two variables with the same name.
However, IMO, it is way simplier to just not have multiple variables with the same name.
When you have a method like the following one:
public void setFoo(Foo foo) {
this.foo = foo;
}
Using this is mandatory. Otherwise, it would assign the argument foo to itself, instead of assigning it to the instance variable.
But that doesn't mean that's the only situation you may use this. The following code is strictly equivalent:
public void setFoo(Foo newFoo) {
this.foo = newFoo;
}
Although in that case, you might very well write
public void setFoo(Foo newFoo) {
foo = newFoo;
}
because this is not necessary anymore. That doesn't make it illegal.
So,
int getValue() {
return time * 5;
}
and
int getValue() {
return this.time * 5;
}
are strictly equivalent.
The keyword 'this' is used to refer to the current Reference object being used. This is just used as syntactic sugar to make it easier to do certain tasks such as invoking constructors in the same class, accessing fields in the same class, parameter types..
Here is an example of two different programming styles. Both do the same thing but the first example uses 'this' to explicitly call the constructor again.
public class Foo {
public Foo() { this("Hello"); } //Explicit constructor call
public Foo(String string) { System.out.print(string); }
}
public class Bar {
public Bar() { new Bar("Hello"); }
public Bar(String string) { System.out.print(string); }
}
The keyword 'this' is often used from within anonymous classes to reference fields in the containing class. For example:
public class App
{
public String myString = "This is Java";
public App()
{
JButton button = new JButton("Test");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0)
{
System.out.println(App.this.myString); // <-- App.this gives access to public fields in App
}});
}
}
This question already has answers here:
Access object created in one class into another
(2 answers)
Closed 10 years ago.
I'm struggeling with accessing an object and it's methods from another class.
I've written some code to illustrate my problem
NOTE: the following code is not compile- or runable, just to explain my issue.
class MainClass {
public static void(String[] args) {
Run r = new Run();
}
}
class Run {
Run() {
Brand cola = new Brand("Coca Cola");
Brand pepsi = new Brand("Pepsi");
// Creates the container object "con1" and adds brands to container.
Container con1 = new Container();
con1.addToList(cola);
con1.addToList(pepsi);
}
}
class Brand {
// In this class I have a method which needs to accsess the con1 object
containing all the brands and I need to access the method
public void brandMethod() {
if(con1.methodExample) { **// Error here. Can't find "con1".**
System.out.println("Method example returned true.");
}
}
}
class Container {
// This class is a container-list containing all brands brands
public boolean methodExample(){
}
}
I am struggling to access the "con1" object from within the Brand class.
How can I get access to "con1"?
I would call Brand with the collection e.g.
brand.addTo(collection);
e.g.
public class Brand {
private Container container;
public void addTo(Container c) {
c.addToList(this);
container = c;
}
}
The brand can then add itself, and hold a reference to the collection. It does mean that the brand has a reference to a single collection, and I'm not sure that's really what you want.
A slightly better solution is to provide the container upon construction of the Brand, and the Brand then adds itself once only to the collection, and has a reference to the collection from the outset.
You must use a reference to the a Container object, and initialize it. Before the error line:
Container con1 = new Container(); <-- the inicialization by creating a new object.
^
|
|
the reference/variable
UPDATE TO ANSWER COMMENT:
You will have to pass the instance; most usually as a parameter to the method. I fear that you have studied the Java basics too little, the question has so many things wrong.
Search the following concepts :
variables and its scopes.
local variable vs instance variable vs static variable.
method parameters.
This question already has answers here:
Is there a way to simulate the C++ 'friend' concept in Java?
(18 answers)
Closed 8 years ago.
How does one implement the friend concept in Java (like C++)?
Java does not have the friend keyword from C++. There is, however, a way to emulate that; a way that actually gives a lot more precise control. Suppose that you have classes A and B. B needs access to some private method or field in A.
public class A {
private int privateInt = 31415;
public class SomePrivateMethods {
public int getSomethingPrivate() { return privateInt; }
private SomePrivateMethods() { } // no public constructor
}
public void giveKeyTo(B other) {
other.receiveKey(new SomePrivateMethods());
}
}
public class B {
private A.SomePrivateMethods key;
public void receiveKey(A.SomePrivateMethods key) {
this.key = key;
}
public void usageExample() {
A anA = new A();
// int foo = anA.privateInt; // doesn't work, not accessible
anA.giveKeyTo(this);
int fii = key.getSomethingPrivate();
System.out.println(fii);
}
}
The usageExample() shows how this works. The instance of B doesn't have access to the private fields or methods of an instance of A. But by calling the giveKeyTo(), class B can get access. No other class can get access to that method, since it a requires a valid B as an argument. The constructor is private.
The class B can then use any of the methods that are handed to it in the key. This, while clumsier to set up than the C++ friend keyword, is much more fine-grained. The class A can chose exactly which methods to expose to exactly which classes.
Now, in the above case A is granting access to all instances of B and instances of subclasses of B. If the latter is not desired, then the giveKeyTo() method can internally check the exact type of other with getClass(), and throw an exception if it is not precisely B.
Suppose A.foo() should only be called by B. This can be arranged by a token that can only be generated by B.
public class B
{
public static class ToA { private ToA(){} }
private static final ToA b2a = new ToA();
void test()
{
new A().foo(b2a);
}
}
public class A
{
public void foo(B.ToA b2a)
{
if(b2a==null)
throw new Error("you ain't B");
// ...
}
}
Only B can generate a non-null B.ToA token. If both A and B do not leak this token to the 3rd party,
nobody else can invoke A.foo()
If A2 wants to friend B too, it needs a different token type. If it's the same token type, since A got a token of the type from B, A can pretend to be B to A2.
The check is done at runtime, not compile time, that is not perfect. Not a big deal though, since any 3rd party can only invoke A.foo() with a null, it can't be an innocent mistake which we want to check at compile time; it's probably malicious so we don't care to warn the caller at compile time.
In Java you can put both (or more) classes into the same package. All methods and fields with the protected qualifier can directly be accessed by all classes in that package.
I figured out another way to achieve the same. Basically you check the fully qualified name of the invoking class name. If it matches your "friend" function, then you give access, else you return null.
public class A {
private static int privateInt = 31415;
public static int getPrivateInt() {
if(Throwable().getStackTrace()[1].getClassName().equals(new String("example.java.testing.B")))
{
return privateInt;
}
else
{
return null;
}
}
}
package example.java.testing;
public class B {
public void usageExample() {
int foo = A.getPrivateInt; // works only for B
System.out.println(foo);
}
}