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.
Related
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.
I know that
class A { }
class B extends A { }
class C extends B { }
is completely legal and I can
C obj = new C();
obj.anyMethodfromA();
is possible.
Now question is this What if I don't want to access class A methods in class C only class B methods should be inherited.
Is this possible?
C anotherObj = new C();
anotherObj.anyMethodfromA(); //can be illegal?
anotherObj.anyMethodfromB(); //should be legal.
You cannot remove classA methods from classC, all you can do is override the classA method in classC and throw UnsupportedOperationException. like
class C extends B {
#override
public void someMethodWasInClassA() {
throw new UnsupportedOperationException("Meaningful message");
}
}
Restricting access for certain subclasses is not possible. You could use interfaces instead to add certain a functionality to a specific class in addition to inheritance.
You can use some sleight of hand using interface to hide the methodFromA but you cannot actually remove it.
class A {
public void methodFromA() {
System.out.println("methodFromA");
}
}
class B extends A {
public void methodFromB() {
System.out.println("methodFromB");
}
}
class C extends B {
}
interface D {
public void methodFromB();
}
class E extends B implements D {
}
public void test() {
// Your stuff.
C obj = new C();
obj.methodFromA();
// Make a D
D d = new E();
d.methodFromB();
// Not allowed.
d.methodFromA();
// Can get around it.
E e = (E) d;
e.methodFromA();
}
There is no such fine-grained inheritance in Java. Once you've marked A methods protected, that extends down the entire heirarchy.
A workaround would be to reimplement the class A methods in class C, throwing appropriate run-time exceptions. But you cannot enforce a compile time failure.
(Note that you could achieve what you want in C++ with friendships: you'd mark the methods private in class A and make class B a friend of class A.)
At the moment C is-a A, however it sounds like you don't want that. So rather than have that maybe C has-a B or B has-a A.
Prefer composition over inheritance.
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());
}
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.
class A is abstract and class B extends class A
now class A reference can hold object of class B,that is
A aObj = new B();
and assume class B has some extra methods....
like
class A
{
public show();
}
class B extends A
{
public show(){}
public method1(){}
private method2(){}
}
now tell me what things variable aObj can access from class B
can it access everything?
aObj only sees the public show() method. If you cast aObj to B, you can then access public method1(). public method2() is only accessible to the implementation of B.
For reference and completeness, here's a list of the possibilities:
A aObj = new B();
aObj.show(); // Works
aObj.method1(); // Error
aObj.method2(); // Error
And with casting to B:
B bObj = (B)aObj; bObj
bObj.show(); // Works
bObj.method1(); // Works
bObj.method2(); // Works inside bObj, but error otherwise
aObj can only use show() as the compiler thinks aObj is of type A, and the only known method of A is show().
If you know that you actually have a B you can cast that object to a B:
if (aObj instanceof B.class) {
B bObj = (B) aObj;
bObj.method1(); //OK
} else {
log.debug("This is an A, but not a B");
}
aObj.show();