I want to desrcibe my question with an example:
Base.java:
public class Base {
//NO annotations
public AnyClass anyObj;
public Base(){}
}
DerivedOne .java:
public class DerivedOne extends Base{
#SomeAnnotionsOne
public AnyClass anyObjWithAnnotations;
public DerivedOne (AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}
DerivedTwo.java:
public class DerivedTwo extends Base {
//These annoations differ from #SomeAnnotionsOne
#SomeAnnotionsTwo
public AnyClass anyObjWithAnnotations;
public Derived_Two(AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}
So i just want anyObjWithAnnotations always be equal to anyObj.
Example main:
public static void main(String[] args){
DerivedOne derivedObj = new DerivedOne(new AnyClass());
derivedObj.anyObj = null;
if(derivedObj.anyObjWithAnnotations == null){
System.out.println("anyObjWithAnnotations : is null");
}
}
Nothing is printed. anyObj is null, anyObjWithAnnotations isn't.
My Question:
Is it possible that anyObj is always the same as anyObjWithAnnotations??
So even if i set one of them to null or create a new instance of AnyClass with new the other variable should have the same new content.
EDIT:
Changed whole example to clarify the problem.
You can use below code, where i am creating object 1 time only and then assign its reference into second object. In this way if a value is changed in one object, in example t1, it will be reflected into t2 as well.
class Test {
private int val;
public Test(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
public class TestSame {
public static void main(String[] args) {
Test t1 = new Test(10);
Test t2=t1;
System.out.println(t1.getVal());
System.out.println(t2.getVal());
t1.setVal(20);
System.out.println(t1.getVal());
System.out.println(t2.getVal());
}
}
O/P :-
10
10
20
20
You can also check that both t1 and t2 has same hashcode value
System.out.println("t1 hashcode "+ t1.hashCode());
System.out.println("t2 hashcode "+ t2.hashCode());
Looks like you need a singleton.
public class Singleton {
private int val = 0;
public void setVal(int val) {
this.val = val;
}
public static final Singleton INSTANCE = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return INSTANCE;
}
}
Usage example:
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
s1.setVal(42);
If singleton is too much for your case you can use approach:
Object obj1 = new Object();
final Object obj2 = obj1;
since obj2 is final reference - you will not be able to change(reassign) it. So, obj2 and obj1 will refer the same Object instance. But it is possible to reassign obj1 reference. If you set final both obj1 and obj2 - you'll get exactly what you want.
final Object obj1 = new Object();
final Object obj2 = obj1;
Related
If I have a singleton class like:
public class MySingleton(){
private static MySingleton istance;
private int element;
private MySingleton(){element = 10;}
public static MySingleton getIstance() {
if(istance == null)
istance = new Mysingleton();
return istance;
}
public void setElement(int i ){
element = i;
}
public int getElement(){
return element;
}
}
and I want to change element's value by calling
MySingleton.getIstance().setElement(20)
Will it change the element value for the istance? Here's an example:
... main () {
MySingleton.getIstance().setElement(20);
System.out.prinln(MySingleton.getIstance().getElement());
// It displays 10, why ?
I suggest you use an enum as it is simpler and thread safe (but not your getter/setter)
public enum MySingleton() {
INSTANCE;
private int element = 10;
public void setElement(int element) { this.element = element; }
public int getElement() { return element; }
}
MySingleton.INSTANCE.setElement(20);
System.out.prinln(MySingleton.INSTANCE.getElement()); // prints 20.
I'm not sure if your code block above was copied in or just retyped, but there were a few basic compilation issues I saw with it - when you're setting MySingleton in getInstance, you need to check capitalization. Also, your class declaration shouldn't have (parentheses). After fixing these two things and running basic main, I got 20.
This is the same as what you had - no synchronization or anything else, but on a single thread it doesn't seem necessary.
public class MySingleton{
private static MySingleton istance;
private int element;
private MySingleton(){element = 10;}
public static MySingleton getIstance() {
if(istance == null)
istance = new MySingleton();
return istance;
}
public void setElement(int i ){
element = i;
}
public int getElement(){
return element;
}
public static void main(String[] args) {
System.out.println(MySingleton.getIstance().getElement());
MySingleton.getIstance().setElement(20);
System.out.println(MySingleton.getIstance().getElement());
}
}
should have an output of
10
20
Im not sure if your code really work, how azurefrog say, make your code synchronized, and in youre line public static getIstance() { you need to set the return type.
I got a array of objects.
From another method i want to print one object from the array, the input to this method must be an integer, that represent the index of the object in the array.
I can't reach the array from printObject(). How do i do this?
public static void main(String[] args) {
Object []obj = new Object[2];
printObject(1);
}
public static void printObject(int i){
if (i == 0){
System.out.println(obj[0].toString());
}
if (i == 1){
Systen.out.println(obj[1].toString());
}
}
You could pass the array to printObject as a parameter (and simplify):
public static void main(String[] args) {
Object[] obj = new Object[2];
printObject(obj, 1);
}
public static void printObject(Object[] objects, int index){
if (index == 0 || index == 1) {
System.out.println(objects[index].toString());
}
}
Because it's declared inside the block of the main method, it will be known only there. Make it a class member or pass it as a parameter.
Example:
private int memberInt;
private void foo() {
memberInt = 5; // :)
int a = 7;
//..
a = 9; // :)
}
private void bar() {
a = 10; // :_(
memberInt = 10; // :)
}
The scope of the variable obj is limited to main method and will not be available in printObject method.
So to get access to variable of type Object[], make Object []obj as class member so that this member will be available through out the class or can be sent as an argument to printObject method.
Check the following code:
public class AccessingMembers
{
static Object []obj = null;
public static void main(String[] args) {
obj = new Object[2];
obj[1] = new Integer(10);//for example
printObject(1);
}
public static void printObject(int i){
if (i == 0){
System.out.println(obj[0].toString());
}
if (i == 1){
System.out.println(obj[1].toString());
}
}
}
If you run the code you'll get 10 as an answer.
either declare a global array which is accessible throughout the class or pass the array as a paramter to the method, so that it can access it.
Object []obj = new Object[2]; is a method variable and it's scope is only to that method.
Here there is one more thing using the above statement you created only two references of the object but not the instances.
//create instances
obj[0]=new Object();
obj[1]=new Object();
try this,
class Test {
static Object[] obj = new Object[2];
public static void main(String[] args) {
printObject(1);
}
public static void printObject(int i) {
obj[0]=new Object();
obj[1]=new Object();
if (i == 0) {
System.out.println(obj[0].toString());
}
if (i == 1) {
System.out.println(obj[1].toString());
}
}
}
This is a practical question, but I am not sure if it has a practical answer. If you have a superclass with let's say 10 subclasses, what is the most simple way to put those 10 subclasses in a collection? Right now (this may be bad design), I have put them in a static collection field in the superclass.
The motivation for this question, however, came because I had obtained the identity of one of the fields of one of the subclasses, but I needed a reference to a different field in the same subclass.
For instance, let's say the subclass has the following fields:
public class SampleSubClass extends SampleSuperClass{
...
private Object1 o_1;
private Object2 o_2;
private Object3 o_3;
...
}
Somewhere else in the program, I have only the identity of o_2, and I wanted to get at o_3.
In theory, there might be an easier way than having to put all of the instances of SampleClass in a collection somewhere. For instance, perhaps in my dreams, there is a software language out there, where the superclass DOES carry information about its subclasses, and the superclass serves as a collection in and of itself.
But nevermind that. To me now, it seems like a good way to put the collection somewhere in the program, is to use a hashmap/hashtable, and to use it as a static member of the superclass.
Please tell me there is a better way. Is there any way to reference field A in an object by having only a reference to field B in an object?
For instance, say I have an ActionPerformed method, it has a source object that is contained in the ActionEvent object parameter. How would I find the instance of the class that owned/contained that source object? What is the best way to design this?
There is no native way to find the owner of a field given the object the field references. The JVM records the number of references pointing to each object so it can do garbage collection, but it doesn't keep track of the owners of the references.
You can store the values of all the fields in a Map which maps them to their owners:
import java.util.*;
public class Super
{
static Map<Object, Super> owners = new IdentityHashMap<Object, Super>();
// IdentityHashMap will not work with primitives due to autoboxing,
// but HashMap requires all field values to have sensible implementations
// of hashCode() and equals().
/** Gets the owner associated with a field. */
public static Object getOwner(Object field)
{
return owners.get(field);
}
/** Establishes ownership over a field. */
protected void own(Object field)
{
owners.put(field, this);
}
/** Removes an ownership, but only if this is the owner. */
protected void disown(Object field)
{
if (owners.get(field) == this) owners.remove(field);
}
/** Shorthand for disown(oldField); own(newField). */
protected <T> T change(T oldField, T newField)
{
disown(oldField);
own(newField);
return newField;
}
}
public class SubA extends Super
{
protected String s;
protected Integer i;
public SubA(String aString, Integer anInt) { setS(aString); setI(anInt); }
public void setS(String aString) { s = change(s, aString); }
public void setI(Integer anInt) { i = change(i, anInt); }
public String toString() { return "SubA(" + s + "," + i + ")"; }
}
public class SubB extends Super
{
protected Object o;
public SubB(Object anObject) { setO(anObject); }
public void setO(Object anObject) { o = change(o, anObject); }
public String toString() { return "SubB(" + o + ")"; }
}
public class Demo
{
public static void main(String[] args)
{
String s1 = "String1", s2 = "String2", s3 = "String3";
Integer i1 = 111, i2 = 222;
Object o1 = new Object(), o2 = new Object();
SubA a1 = new SubA(s1, i1), a2 = new SubA(s2, i2);
SubB b = new SubB(o1);
p("s1 owner = %s", Super.getOwner(s1)); // SubA(String1,111)
p("s2 owner = %s", Super.getOwner(s2)); // SubB(String2,222)
p("s3 owner = %s", Super.getOwner(s3)); // null
p("i1 owner = %s", Super.getOwner(i1)); // SubA(String1,111)
p("i2 owner = %s", Super.getOwner(i2)); // SubA(String2,222)
p("o1 owner = %s", Super.getOwner(o1)); // SubB(java.lang.Object#...)
p("o2 owner = %s", Super.getOwner(o2)); // null
p("s1 -> s3, o1 -> o2");
a1.setS(s3);
b.setO(o2);
p("s1 owner = %s", Super.getOwner(s1)); // null
p("s3 owner = %s", Super.getOwner(s3)); // SubA(String3,111)
p("o1 owner = %s", Super.getOwner(o1)); // null
p("o2 owner = %s", Super.getOwner(o2)); // SubB(java.lang.Object#...)
}
static void p(String fmt, Object... args)
{
System.out.format(fmt, args);
System.out.println();
}
}
Or you could make the field values themselves maintain a reference to their owner, either through inheritance or using a wrapper class:
public class OwnableObject
{
protected Object owner;
public OwnableObject(Object anOwner) { owner = anOwner; }
public Object getOwner() { return owner; }
public void setOwner(Object anOwner) { owner = anOwner; }
}
public class MyString extends OwnableObject
{
protected String str = null;
public MyString(Object anOwner) { super(anOwner); }
public String toString() { return str; }
public void set(String aString) { str = aString; }
}
public class FieldWrapper<E> extends OwnableObject
{
protected E value = null;
public FieldWrapper(Object anOwner) { super(anOwner); }
public E getValue() { return value; }
public void setValue(E aValue) { value = aValue; }
}
public class Demo
{
protected MyString s = new MyString(this);
protected FieldWrapper<Integer> i = new FieldWrapper<Integer>(this);
public void setS(String aString) { s.set(aString); }
public void setI(int anInt) { i.setValue(anInt); }
public String toString() { return "Demo(" + s + "," + i.getValue() + ")"; }
public static void main(String[] args)
{
Demo d1 = new Demo();
Demo d2 = new Demo();
MyString f1 = d1.s;
FieldWrapper<Integer> f2 = d1.i;
OwnableObject f3 = d2.s;
OwnableObject f4 = d2.i;
d1.setS("one");
d2.setS("two");
d1.setI(1000);
d2.setI(2000);
p("f1 = %s, owner = %s", f1, f1.getOwner());
p("f2 = %d, owner = %s", f2.getValue(), f2.getOwner());
p("f3 = %s, owner = %s", f3, f3.getOwner());
p("f4 = %s, owner = %s", f4, f4.getOwner());
}
static void p(String fmt, Object... args)
{
System.out.format(fmt, args);
System.out.println();
}
}
Answering your direct question: how to easily define a collection containing a given set of classes?
public class ClassA {
private final List<Class<? extends a>> knownSubclasses = Arrays.asList(ClassB.class, ClassC.class);
};
class ClassB extends ClassA {}
class ClassC extends ClassA {}
Answering your motivation: how to access a field in a subclass without declaring it for the super class?
public class SomeSuperclass {
protected Object3 getObject3() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
public class SomeSubclass extends SomeSuperclass {
private final Object3 object3 = null;
#Override
protected Object3 getObject3() { return object3; }
}
Maybe recognize instances having an object3 by the use of interfaces
public interface MyClassWithObject3 { Object3 getObject3(); }
...
void someOperation(SomeSuperclass that) {
if (that instanceof MyClassWithObject3) { ... }
}
You could also use named properties
void someOperation(SomeSuperClass that) {
Object3 object3 = that.getProperty("object3");
}
I have a getter setter class named SharedData.java . I am getting null pointer exception when I'm going to imply it on my code . Here is the SharedData class :
public class SharedData {
private static SharedData instance = null;
public SharedData() {
// randomizeServers();
}
// data to be shared
private double src_latitude = -1;
private double src_longitude = -1;
private double end_latitude = -1;
private double end_longitude = -1;
//Getter-Setters
public static SharedData getInstance() {
return instance;
}
public static void setInstance(SharedData instance) {
SharedData.instance = instance;
}
public double getSrc_latitude() {
return src_latitude;
}
public void setSrc_latitude(double src_latitude) {
this.src_latitude = src_latitude;
}
public double getSrc_longitude() {
return src_longitude;
}
public void setSrc_longitude(double src_longitude) {
this.src_longitude = src_longitude;
}
public double getEnd_latitude() {
return end_latitude;
}
public void setEnd_latitude(double end_latitude) {
this.end_latitude = end_latitude;
}
public double getEnd_longitude() {
return end_longitude;
}
public void setEnd_longitude(double end_longitude) {
this.end_longitude = end_longitude;
}
}
Here is my code :
SharedData sharedData ;
sharedData = SharedData.getInstance();
sharedData.setSrc_latitude(latitude);
sharedData.setEnd_longitude(longitude);
Can anybody please help me with this ? Thanks .
You never initialized sharedData, so its value is null, calling a method on it got your program to crash.
I think you're trying to use Singleton Pattern. Try the below:
private static SharedData instance = new SharedData(); \\ Initialize here
private SharedData() { // Make it private....
// randomizeServers();
}
// data to be shared
private double src_latitude = -1;
private double src_longitude = -1;
private double end_latitude = -1;
private double end_longitude = -1;
//Getter-Setters
public static SharedData getInstance() {
return instance;
}
SharedData.getInstance();
Returns null. Later you're trying to call a method on it:
sharedData.setSrc_latitude(latitude);
Which is illegal as reference to object is still null.
You don't instanciate the class, so getInstance() returns null.
At the start of your class, replace :
private static SharedData instance = null;
by :
private static SharedData instance = new SharedData() ; // creates a new instance
change private static SharedData instance = null;
to private static SharedData instance = this;
and make your class static
public static class SharedData {
Also , make the getters setters static..
Even using the singleton pattern you should instantiate the object SharedData at least once.
try this
SharedData sharedData = new SharedData();
sharedData = SharedData.getInstance();
sharedData.setSrc_latitude(latitude);
sharedData.setEnd_longitude(longitude);
I am creating a certain class using
MyClass class1 = new MyClass(ClassA.StaticSet1, ClassA.StaticCoef1);
MyClass class2 = new MyClass(ClassB.StaticSet1, ClassB.StaticCoef1);
so I wanted to gather all these static values in one class and call them using something like
MyClass class1 = new MyClass(TopClass.Obj1);
MyClass class2 = new MyClass(TopClass.Obj2);
where Obj1 and Obj2 are static entities containing the abovementioned pairs of values.
the closest thing I could do was creating static classes inside TopClass and extending one base class
so I got this ugly implementation
Public class TopClass{
public static class Base{
public String set[];
public double coef[];
public Base(s, c){
set = s;
coef = c;
}
}
public static class Obj1 extends Base{
public static String set[] = {"a","b","C"};
public static double coef[]= {1,2,3};
public Obj1(){
super(set, coef);
}
}
public static class Obj2 extends Base{
public static String set[] = {"x","y","z"};
public static double coef[]= {11,12,13};
public Obj2(){
super(set, coef);
}
}
}
then I call them with
Myclass class1 = new MyClass((TopClass.Base)(new TopClass.Obj1());
Myclass class2 = new MyClass((TopClass.Base)(new TopClass.Obj2());
but this wasn't what I exactly wanted because the class became cumbersome especially that I will be creating many of these entries.
any insight would be much appreciated :)
thanks,
Hani
This would be a great place to use a Factory pattern. Maybe something like:
public class SetCoefProvider {
private String[] set;
private double[] coef;
public SetCoefProvider(String[] set, double[] coef) {
this.set = set;
this.coef = coef;
}
public String[] getSet() {
return set;
}
public double[] getCoef() {
return coef;
}
}
public class SetCoefProviderFactory {
public static SetCoefProvider createObj1Provider() {
return new SetCoefProvider(new String[] {"a", "b", "c"}, new double[] {1,2,3});
}
public static SetCoefProvider createObj2Provider() {
return new SetCoefProvider(new String[] {"x", "y", "z"}, new double[] {11,12,13});
}
}
and then if you really want them to be singletons, you can always do something like:
public class SingletonSetCoefProviders {
private static SetCoefProvider obj1Provider, obj2Provider;
static {
obj1Provider = SetCoefProviderFactory.createObj1Provider();
obj2Provider = SetCoefProviderFactory.createObj2Provider();
}
public static SetCoefProvider getObj1Provider() {
return obj1Provider;
}
public static SetCoefProvider getObj2Provider() {
return obj2Provider;
}
}
I will be creating many of these entries. any insight would be much appreciated :)
The idea is that with statics, you don't want to make many of them, that's the whole point of a static thing. Rethink and/or re-ask with more context about your goals, what you're intending to accomplish isn't clear.
i would encapsulates the Object1 and object2, the why is to make sure that they are available to use and access, at least they are not null. see below:
public static TopClass(){
private static Object obj01 = null;
private static Object obj02 = null;
public Object getObj01(){
if(obj01 == null){
obj01 = new Object();
}
return (obj01);
}
public Object getObj02(){
if(obj02 == null){
obj02 = new Object();
}
return (obj02);
}
}
or in your case the objects are in array tipe [],.
i don't get the static part. why not do something like:
import java.util.*;
interface Foo {
String[] set();
double[] coef();
}
class FooImpl1 implements Foo {
#Override public String[] set() {
return set;
}
#Override public double[] coef() {
return coef;
}
String set[]={"a","b","C"};
double coef[]={1,2,3};
}
class FooImpl2 implements Foo {
#Override public String[] set() {
return set;
}
#Override public double[] coef() {
return coef;
}
String set[] = {"x","y","z"};
double coef[]= {11,12,13};
}
interface Bar {
Foo foo1=new FooImpl1();
Foo foo2=new FooImpl2();
}
public class So9577640 {
public static void main(String[] args) {
Foo foo1=new FooImpl1();
System.out.println(Arrays.asList(foo1.set()));
Foo foo2=new FooImpl2();
System.out.println(Arrays.asList(foo2.set()));
System.out.println(Arrays.asList(Bar.foo1.set()));
System.out.println(Arrays.asList(Bar.foo2.set()));
}
}