In some way I'm trying to avoid multiple reference to an specific object. I have the following:
public class A
{
private C c;
public A()
{
this.c = new C();
}
public C getC()
{
return this.c;
}
}
Then I have:
public class B extends A
{
private C c;
public B()
{
super();
}
public void someMethod()
{
// I want to avoid this
this.c = getC();
// But I want to allow the execution of methods inside C
getC().someMethodOfC();
}
}
I guess that in C++ it could be done with some operator overloading but I've seen that in Java this is not possible.
Is there any way to only have one reference of the object in Java (And don't allow the creation of more references)
I don't think I understand your question fully. You may make C a private inner class in A, expose a method in A that uses C to perform the operations/actions that you want.
Remove private C c; in class B. By extending B from A, you have access on public and protected members of A. This includes public C getC() of class A. If you want direct access on member c of A in B, make c protected.
Related
Recently in an interview for Java Developer role, I was asked how do I make Class A immutable if it has a member variable, which is an object of Class B and in a situation where Class B is external to the project and cannot be edited by the programmer moreover class B might even have a member variable of its own which is an object of another user defined class. I gave it a lot of thought and told the interviewer there is no way unless class B has implemented and exposed a method to deep clone itself.
The interviewer though wasn't convinced. Is there really a way to make such a class immutable?
If I can remember correctly this was the situation he explained. He wanted me to make class A immutable, what would have been the best answer?
final public class A {
final private B b;
A(B b) {
this.b = b; // Class b might/might not be cloneable
// this.b = (B)b.clone();
}
public B getB() {
return b;
// return (B)b.clone();
}
}
class B // external cannot edit
{
C c;
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
}
class C // external cannot edit
{
int i;
String j;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getJ() {
return j;
}
public void setJ(String j) {
this.j = j;
}
}
Don't expose B to the world. So do not have a method which return B.
Instead identify the methods in B, which don't mutate B and let A implement these methods by calling the same method in b.
So if B has a method calcSomething() a should have a calcSomething() methocd which just does return b.calcSomething().
You may use something like this:
final public class A {
final private B b;
A(B b) {
this.b = cloneB(b);
}
public B getB() {
return cloneB(b);
}
private static B cloneB(b){
B newB = new B();
C c = new C();
c.setI(b.getC().getI());
c.setJ(b.getC().getJ());
newB.setC(c);
return newB;
}
}
It that case Class A is 100% immutable.
Update: Also you can use reflection or seralization to get deep copy of class (if class has deep hierarchy), for example using GSON for seralization:
private static B cloneB(b){
String tmp = new GSON().toJson(b);
return new GSON().fromJson(tmp, B.class);
}
or so on
I have a class A with a number of setter/getter methods, and want to implement a class B which "extends A" and provides other functionality.
I cannot modify class A, and it doesn't have a clone or constructor method that that takes a class A obj as a parameter. So basically I implement class B such that
it has a constructor that takes a class A obj as a parameter and keeps a copy of this obj
when we call setter/getter methods on B, it delegates to the class A obj
other functionality...
Class A has many setter/getter methods and I feel this implementation is not clean but not sure how to fix this. Usually I can make B extend A, but in this case I have to be able to take a class A obj as a parameter for the constructor.
I'm sorry if the question is not clear enough, please let me know if you need more clarifications. Thanks.
Example:
public class A {
private int x;
public void setX(int x) { this.x = x; }
public int getX() { return this.x; }
}
public class B {
private A a;
public B(A a) { this.a = a; }
public void setX(int x) { a.setX(x); }
public int getX() { return a.getX(); }
public void foo() { ... };
public void bar() { ... };
}
Basically A has a lots of properties X/Y/Z... and has many setters/getters. If I do this then B have many dummy setters/getters which simply delegate to the same call on a. Is there a cleaner way to implement this?
I think you're trying to extend an object of class A to add functionality to it and this is creating this dilemma. You can't copy A easily with a copy constructor and so you're trying to use composition rather than inheritance, and then that's not working.
Three options:
Do what you're doing - wrap the object of type A as something owned by B and delegate - it works and it's not too bad
Subclass A with B and then use some sort of reflection based copy routine to copy all properties from the object of type A into the new object of type B - e.g. http://commons.apache.org/proper/commons-beanutils/ copyProperties function
Create a copy constructor in class B that does what you want
Example
public class A {
private int x;
public void setX(int x) { this.x = x; }
public int getX() { return this.x; }
}
public class B {
public B(A a) {
// copy all A properties from the object that we're going to extend
this.setX(a.getX());
}
.. other stuff
}
The problem you're describing is one of extending an object. Extending a class is straightforward - just subclass it, and you have the base implementation plus your new stuff. To extend an object with the above code:
A someA = new A();
// a is initialised as an A
B aWithExtraProperties = new B(someA);
// now you have a B which has the same values as the original A plus
// b's properties
// and as B subclasses A, you can use it in place of the original A
I've tried changing an object's type at runtime like this before and it doesn't feel nice. It may be better to consider why you're doing this at all and whether there are alternatives.
If class B extends class A, it will automatically inherit all its non-private non-static methods. In your code, the getter/setters in class A are declared public, so class B will inherit them.
However, for this to work, you will need to rewrite class B's signature as follows, abd remove pretty much all code you wrote in B's body :
public class B extends A {
// here, put any functionalities that B provides in addition to those inherited from A
}
This way, you can access all the getter/setters through any reference of type A or B, like this :
public static void main(String... args) {
A a = new A();
a.setName("Bob");
System.out.println(a.getName());
B b = new B();
b.setName("Joe");
System.out.println(b.getName());
// And even this, thanks to polymorphism :
A ab = new B();
ab.setName("Mike");
System.out.println(ab.getName());
}
I have a method dummy with A as class parameter, but i need to pass instance of subclasses B to that method. I know from:
Does Java casting introduce overhead? Why?
that downcasting in java have overhead. Most of my code deal with subclass B so i dont use downcasting for this purpose. Instead i use temporal instance variable cc for that purpose. But this is not make a change for object of subclass m. I need change in variable cc avaliable too for instance variable m. This is my code:
public class TestCast {
public TestCast() {
B m = new B(12, 3);
dummy(m);
A cc = m;
dummy(cc);
System.out.println(m.a);
System.out.println(cc.a);
}
public void dummy(A t) {
t.a = 22222;
}
public static void main(String[] args) {
new TestCast();
}
}
class A {
public int a = 0;
public A(int a) {
this.a = a;
}
}
class B extends A {
public int a;
public int b;
public B(int a, int b) {
super(a);
this.a = a;
this.b = b;
}
}
with output
12
22222
In your particular example, both the parent and child classes declared a field with name a. In this case, the child variable hides the parent variable.
Also, variables/fields are not polymorphic entities like methods. They are accessed by the static type of a reference.
In other words, the field access
A var = new A(10);
var.a; // returns 10
And the field access
A var = new B(1501, 10);
var.a; // also returns 10
but
A var = new B(1501, 10);
var.a; // returns 10
((B)var).a; // returns 1501
because you access a on a reference with static type B.
In your method
public void dummy(A t) {
t.a = 22222;
}
The static type of t is A so you will modify the value of the parent class variable.
Casting is telling the compiler that a reference variable is of specific Type at runtime
Because B is extending A you do not want to re-define the variable a
In answer to your comment, you code should be something like:
class B extends A {
public int b;
public B(int a, int b) {
super(a);
this.b = b;
}
}
IMO, your example code is not perfect implementation of inheritance. Inheritance enables you re-usability of code. In other words, you don't need to declare int a again in class B.
I need change in variable cc avaliable too for instance variable m:
However, if you want to change in variable cc as well, then declare variables a, b as private/protected in both A and B. And provide setters and getters in both classes.
And in class B call super.setA(a) like below.
class B extends A {
private int a;
private int b;
public B(int a, int b) {
super(a);
this.a = a;
this.b = b;
}
public setA(int a) {
super.setA(a);
this.a = a;
}
}
SITUATION: Say there is a class A and an interface B.
REQUIREMENT: If any class, say C, wants to create objects of A and use them, then that class will also have to implement interface B.Is there any way to enforce this condition?
WHY: Now a question may arise as to why I want to do such a thing. The reason is that when a class C creates objects of A and uses them, then those objects call certain methods of C. I want to declare those methods in interface B, so that C will invariably implement those methods.
Try this snippet:
public interface B {
// methods
}
public class A {
private final B b;
public A(B b) {
this.b = b;
}
...
}
public class C implements B{
// implement B's methods
public static void main(String[] arg) {
C c = new C();
A a = new A(c);
}
}
Since you say that objects of class A will call methods on C, they will have to keep reference to C somehow. Make this reference of type B and you are done.
That is
public class A {
public A(B arg) {
....
}
}
Then in C:
A a = new A(this);
That will force class C to implement interface B.
I have a Java class B with an inner class C. Some methods of B accept an instance of C as parameter but I only want to accept C instances created by the proper instance of B. Is there a way to do this validation at compile time?
Example
C c1 = new C();
B foo = c1.getB(); // foo was created by instance c1
C c2 = new C();
c2.method(foo); // I want a compiler error here.
My case
Have a class names Map which hold a matrix of instances of the inner class MapArea. The nice thing about this scheme is that I can validate the xPos, and yPos fields at the constructor so no invalid Areas for a given map are built. The map as a method distanceFrom(MapArea startingPos, MapArea toLocation, MapArea... otherLocations) and I was trying to avoid to validate the map area arguments again.
If this is really the behavior you want, method() should really be defined in the inner class.
In other words, instead of:
public class C {
//...
public void method(B b) {
this.x = b.y;
//...
}
//...
public class B {
//...
}
//...
}
It should be:
public class C {
//...
public class B {
//...
public void method() {
C c = this.C;
c.x = this.y;
//...
}
//...
}
//...
}
Of course, this wouldn't solve the problem if, for example, you wanted public void method(B b1, B b2, B b3), where all three instances of B are enclosed by the same instance of C.
A compile error won't work, but you can at least throw an exception:
public class C
{
public static void main (String [] args)
{
C c1 = new C();
B b = c1.getB();
c1.useB(b); //OK
C c2 = new C();
c2.useB(b); //throws IllegalArgumentException
}
public B getB() { return new B(); }
public void useB(B b) {
if(b.getC() != this)
throw new IllegalArgumentException();
//...
}
private class B
{
public C getC() { return C.this; }
//...
}
}
There's no way (AFAIK) of doing this at compile time.
At runtime you can do it by having the outer instance's factory method pass a reference to itself to the inner instance's constructor.
The inner class would need to store that reference, such that the outer class can check whether it created that instance or not:
public class C {
public class B {
private C parent;
private B(C parent) {
this.parent = parent;
}
public C getParent() {
return parent;
}
}
public B getB() {
return new B(this);
}
public void method(B b) {
assert(this == b.getParent());
}
}
Actually, as Kip's concurrent answer shows, B can access C.this to get the parent object so there's no need to store the parent reference. However the method above would be necessary if C wasn't actually an inner class.
If you make the constructor of the inner class (C) private, I believe the enclosing class (B) can still instantiate it while other classes cannot. This ensures that only B and C can instantiate C.
Edit: I've verified that with a small mockup. Make the inner class constructor private, and then only the inner class (C) or the enclosing class (B) can instantiate it.
See http://tns-www.lcs.mit.edu/manuals/java-1.1.1/guide/innerclasses/spec/innerclasses.doc6.html for more. In particular: "Access protection never prevents a class from using any member of another class, as long as one encloses the other, or they are enclosed by a third class.".
There's no compile-time way to guard against instance-specific usage. Your best bet is probably throwing an Exception when the usage in incorrect. Another option you have is to have the parent class to have a Map of instances of the inner class, and to have other classes tell the outer class to operate on the inner class not by the instance but by some other references. This will work with other classes don't need to do anything directly with the inner class.