Identical classes casting? - java

Suppose I have two classes A and B. Both are identical (same atributes, methods, etc), but they are named different.
There's some safe way, in Java, to cast a B object as an A object?

No, you cannot cast one to the other if they belong in different class hierarchies. They are not identical, even if they happen to share the same attributes and methods. Additionally, if they belong to the same class hierarchy, but one is not a superclass of the other, you can't cast across the same class hierarchy either. There's only upcasting and downcasting within a hierarchy.
However, you can pass objects of either class to a certain method if
They implement the same interface, or extend the same superclass, and
That method accepts a parameter that is of the interface's or superclass's type
(And that's the basic premise of polymorphism.)

No you can't, unless they have a common parent with the same attributes, but you can use the copyProperties() method from common.beanutils to pass every property from one bean to another.
Another way would be to create a subclass for A which could delegate calls to a B and vice versa.
A third way would be to use a proxy.
But the last two solutions only works for method calls, if your attributes are public you can't do anything.

Probably, you could use reflection to copy properties.
Then, create a wrapper function to "cast" the class; example:
class A {
public cc=0;
}
class B {
public cc=2;
}
B mycast(A a){
B b=new B();
for(String name in a)
b.setProperty(name,a.getProperty(name));
return b;
}
Notes:
Been some time since I've used Java, so the above should be seen as pseudo-code more or less, especially the JS-style reflection.
I suggest you use an interface instead; they were made specifically to do what you want (and more, of course).

Formally speaking the only way two Java classes can be identical is if they satisfy the identity a == b. Two classes with the same members and different names or packages don't do that, also by definition.

The only way is to manually set the data in class A to the data in class B

Related

Can you access sub class variable via super class in Java

Can I access my subclass variable via super class instance?
For instance I create my super class object in Main, and then I want to know the value of variable in the sub class. Is it possible to do so? Thanks.
No this goes against the inheritance principle. It is like asking if a previous gen device will have access to the newer features introduced in the next gen device based on this.
A subclass can access non private members of parent class but not vice versa. It doesnt make sense as the language syntax doesn't ever allow access to child from parent while the opposite is possible through methods and keywords like super.
So it is better that you rethink the way you are thinking of using inheritance abd refactor your core to meet the requirement as this certainly wont work
If class B extends class A and you have an A object, then you can always convert it to its subclass, B in this case. Consider the following:
A a = new A();
B b = (B)a;
afterwards, you can always reach B members via b. You can do it in an inline manner as well, via ((B)a).

Is there an elegant way to change what methods/variables an object of a class can use based on the constructor used to create this object?

So for example, when the object is constructed with lets say a constructor without arguments, this object is able/"allowed" to use a certain subset of the methods defined in the class, and when the object is created with a different constructor (for example with arguments) it is able/"allowed" to use a different subset of the methods defined in the class.
These are the conceptual solutions that spring to mind:
Use reflection in the constructors to modify the visibility/accessibility of its class methods. (Problem with this is EURGH... reflection)
Set boolean flags like isAllowedToUseMethodA in the constructor to identify which methods the object will be allowed to use. (Problem with this is the overhead the boolean checks will impose and also methods which are flagged as inaccessible will still be visible to the object and can be attempted to execute)
The obvious elephant in the room answer to this is "Make 2 different classes." and I understand that, I'm just curious is there an elegant way to do this if I want to do this in a single class?
Both options 1 and 2 have a multitude of problems, however fortunately there is a simple and reasonably elegant way to do exactly what you want:
Use inheritance.
Define different versions of the object all inheriting off a common (potentially abstract) core.
Then have factory methods that construct the correct version of each one depending on which factory method you call.
You can't actually use a different subset of methods, but you can kind of 'switch' by means of the strategy pattern.
E.g. for your constructors you set different strategies:
public class XXX() {
method1Strategy = new method1Strategy1();
method2Strategy = new method2Strategy1();
}
public class XXX( ... ) {
method1Strategy = new method1Strategy2();
method2Strategy = new method2Strategy2();
}
And in your methods you execute the concrete strategy:
public Object method1(...) {
return method1Strategy.execute(...)
}
public Object method2(...) {
return method2Strategy.execute(...)
}

Decorator Design Pattern in java

I'm designing of a project I have to do. For that, I have thought to use decorator design pattern. However, I have to adjust my design to the existing implementation of the project. Then, I can't keep completely the decorator design pattern.
The project has an abstract base class (called A) and a set of sub-class (called A1, A2, A3, A4, etc.). I can't modify the code of these classes.
Then, I have to add extra funcionality to these classes. For that, I create an abstract class (called B) that use to class A (Decorator). I also create concrete decorators that use to classes A1,A2,A3,A4,...
NOTE: As you see, I don't use any interface because the class A doesn't use any interface and I can't modify this code.
But I see some issues in this design:
1) Classes B1,B2,B3,B4,... have to add all methods of classes A1,A2,A3,A4,... for calling to methods of classes A1,A2,A3,A4... For example, in class B1:
class B1 {
public A1 objectA1;
B1() {
objectA1 = new A1();
}
public void add(int value) {
objectA1.add(value);
// extra funcionality
}
}
It can be a problem because if other developers modify the code of classes A,A1,A2,A3,A4,... they also need to modify the code of B,B1,B2,B3,B4,...
I WANT TO PREVENT THAT.
2) Moreover, classes A,A1,A2,A3,A4 have protected methods that only can be accessed from the own class or sub-classes. As I need to access to these methods, I can't use the decorator design pattern.
SECOND ALTERNATIVE
I could extend the classes A1,A2,A3,A4 with B1,B2,B3,B4. For example:
class B1 extends A1 {
B1() {
objectA1 = new A1();
}
public void add(int value) {
super.add(value);
// extra funcionality
}
}
Of this way, I solve the second problem and avoid to override all methods of A1, overriding only necessary methods. Even so, each time a sub-class of A is created, it's necessary to create the corresponding class B.
I WANT TO PREVENT THAT because it only is necessary that class B (B1,B2,...) override a method of class A (A1,A2,...).
THIRD ALTERNATIVE
Then, I thought that I could consider to class B (B1,B2,...) as a wrapper of class A (A1,A2,...). Of this way, a instance of B will be created as next:
new BMaker.get(A1, params_of_constructor_A1)
new BMaker.get(A2, params_of_constructor_A2)
new BMaker.get(A3, params_of_constructor_A3)
new BMaker.get(A4, params_of_constructor_A4) or
...
new BMaker.get(AN, params_of_constructor_AN)
where BMaker.get is a static method.
public static <T extends A> A get (T objectA, params ) {
// return anonymous class (*1)
}
My question is if it's possible to implement an anonymous class that inherit of A1, A2, ...
Each call to BMaker.get() should be created a different anonymous class deppending on if the first parameter of BMaker.get() is A1,A2,A3,...
Really, I don't know if it's possible to do this or is there another better way.
Any help would be appreciated!
Answer to the first issue:
Either put an interface I on A so your decorators/delegates can implement same interface, or
Create an interface I (equivalent to A's api) and a wrapper class AW which wraps A and implements I by passing all calls straight onto it.
Convert your client code to use I rather than A, and you can then happily proceed to build decorators/ or delegates using the new interface having "wrapped up" the old crunk in AW.
The one notable issue that arises is that some styles of code using A (IdentityHashMaps, persistence) may want a reference to the "underlying" A. If that comes up, you can put a method in the interface getUnderlyingA(). Try and avoid using that too much, since it obviously bypasses all decoration.
Second issue: decorating subtypes.
The question here is whether the subtypes need to be exposed as different decorator types -- or whether one uniform decorator can be exposed, that (maybe, if necessary) is internally aware of the type-system of the A subtypes that it can wrap.
If the subtypes are well-known & stable, you can implement a "handle style" api in the interface. For example, for file-system entities, you would present a handle of a single type but offer isFile(), isDirectory(), isDevice(), isDrive(), isRaw() etc methods for interrogating the type. A listFiles() method could be available to use the directory subtype.
My question is why you need external access (from the decorator) to protected methods? If you do, those methods should be public and the original design is broken/insufficiently extensible.
Maybe you can create a static helper class in the same package (if not changing the A class itself) that will give you proper access to this legacy crunk from your decorator.
There's a certain point here, where doing your job properly does sometimes involve working with & potentially upgrading legacy code. If there isn't an efficient & maintainable design alternative, that shouldn't be a total sticking point. Doubling up the type-system (creating two parallel heirarchies) is definitely not what you should be doing.
If there isn't a good way to do this, you should work on something else (a different feature/requirement) rather than making the codebase even worse.

Why does java.lang.Math extend java.lang.Object?

According to the Java API for the Math class, Math extends the Object class:
public final class Math extends Object
However, Math does not inherit Object's methods, and you also cannot construct a Math object (EDIT: this statement is false and partly false; see below).
My question is then why is this done? If it is an object, then it should have the bare-bones methods from Object. If it is not an object, then I feel like it should not be extending Object.
And, assuming there is a good reason for extending Object, how is it done? In other words, how are the inherited methods and constructor suppressed?
Math is the foremost example in my mind of this kind of static definition class (I guess you'd call it that?), but this question may also apply to classes that have a similar purpose.
EDIT: So I'm aware that all classes implicitly extend Object. What's bothering me is that to me there's a logical disconnect between the notion of an "object" in theory-- something with a state and associated functionality-- and what's being done here.
Object is the super class of everything. All classes extend Object
Math does inherit Object's methods. Every class in Java ultimately has to inherit from Object. But since you can't construct Math objects, it doesn't matter. The methods are inherited, but without being able to construct an instance you can't ever use them from Math.
Every class implicitly extends Object unless they extend another class (Java doesn't allow multiple inheritance).
Still! by extending another class you're, in the very end, extending Object, because the last class that doesn't extend another particular class extends Object.
The concept behind this "default inheritance" can be extracted directly from Object's JavaDoc:
Class Object is the root of the class hierarchy. Every class has
Object as a superclass. All objects, including arrays, implement the
methods of this class.
EDIT: Math does inherit Object's methods. It does not override them tough and the calls are derived to the implementations of the superclass.
You should pay attention to an important aspect of the Math class. The constants and methods it defines are mainly static. Mathematical functions do not depend of a particular instance of the class because those calculations are independent of the context.
You have no particular reason to create an instance of the Math class and that's why its constructor is not visible. You cannot do Math m = new Math() and that's why you don't see methods such as equals or hashcode. In particular since the class is final and can't be extended, you cannot create a sublclass that defines them. IMHO it would be pointless.
Object is the super class of every java class. An you are mistaken that Math does inherit object's methods.
If you want more see the source.
http://www.docjar.com/html/api/java/lang/Math.java.html

General programming question about scope

This is more of a general programming question so the code examples I give will just be pseudo-code. I program in C++, Java, and Python so the pseudo-code is a mix of those. I am not too sure what the name of this is called so if you could give me a name for this, I can Google for more information about it I would greatly appreciate it.
Let's say I have a class called A. In this class, I create an instance of a class called B:
class A {
//instance variables
classB;
variable1;
variable2;
//instance methods
instanceFunction(parameter1, parameter2) {
//Do Stuff
}
function1(parameter1) {
classB = new B(some parameters);
}
setVariable1(value) {
variable1 = value;
}
getVariable2() {
return variable2;
}
}
In class B, I want to make changes to or make use of instance variables in class A. I can do this by passing a reference to A into B. So my A::function1 would look like this:
function1(parameter1) {
variable1 = new B(this, other parameters);
//Python syntax:
//variable1 = B(self, other parameters)
}
and my class B would look like this:
class B {
//instance variables
parentClass;
variable2;
//instance methods
instanceFunction(classA, other parameters) {
parentClass = classA;
}
function1() {
parentClass.setVariable1(someValue);
}
function2() {
variable2 = parentClass.getVariable2();
}
}
What other ways are there to have use of the variables in class A inside of class B?
If the code was C++ or Java, assume all variables are private and all methods and functions are public. Also assume all variables are passed by references or a pointers.
Edit:
First, thanks for all the responses!
Some clarification:
The reason I am asking this question is I have done a good amount of Qt programming in C++ and Python. In Qt, there are signals and slots. This lets inner objects tell the outer object to do something. For example I have an object A with objects B and C inside of it. Some change happens to object B and B needs to let A and C know. So B will emit a signal. A will catch this signal and do what it needs to do. Then, A will also let C know that B emitted this signal. This way C can do what it needs to do.
The reason I asked my question is because I was wondering how I can do something like I described without using the Qt libraries.
Also, let's assume B "is not" an A so I can't/don't want to use inheritance.
I am not too sure what the name of this is called...
I am having trouble following your pseudo-code, but you might be able to accomplish what you're looking for via:
Inheritance, which allows derived classes to access protected variables from a base class (static or instance variables)
Friend functions (C++) (which allows functions to have access to private instance variables on a class)
Dependency Injection (But probably only if you have more complex requirements than you're actually stating in your question. In this super-simple case, you'd just be accessing public properties or fields when an instance is passed in to a function - you might have to access them through a public getter/setter, since you want the variables to be private)
Edit:
After your edits, it is pretty clear that you want the Observer Design Pattern. This allows you to decouple the code that responds to a state change from the code that signals the state change.
That pattern is less about access to variables (as my first links were about), than it is about responding to events (or "state transitions", if you think about your class as a Finite State Machine).
Given the edit you made; It may be practical to implement a sig/slot mechanism using boost::signals, or the threadsafe signals2 (also in boost). This is implying that you are looking for a behaviour similar to Qt's sigslot mechanism. There are also many alternatives, look at the SO question here.
Explicitly passing this (or perhaps a proxy around this) is pretty much the only (sane, anyway) way to do it, assuming they need to be seperate objects. An object can't and shouldn't need to know number and location of its references. And even if you could get a list of all references to itself, that list could easily contain local variables, items in collections, potentially several instances of A, etc. - how is it supposed to know which one to chose as its parent?
If a B actually "is an" A, you should just make it a subclass.
What other ways are there to have use of the variables in class A
inside of class B?
Since your variables are not static, they are instance variables, so variable1 and variable2 are only meaningful in the context of a specific instance of A - so there needs to be a reference to that instance, not matter how you shape it.
For example, inner classes in Java can use variables of the enclosing outer class directly, but in reality this is just an illusion maintained by the compiler, and in the bytecode, the inner class actually keeps a reference to the outer class instance.
In C++, there is a concept of friend classes: a class A can declare another class B to be its friend, something which gives B access to the private variables of A. Simply write friend class B; inside of A. (As #delnan reminds us, you still need to manually give B a reference to A.)
In Java, if you declare B inside of A, B will become an inner class. Inner classes can only be instantiated from an instance of the outer class, and the instance of the inner class will be tied to the corresponding instance of the outer class, and may access its private variables.
(I agree with #mellamokb, though: This is probably a bad idea, as it creates very tight coupling between the two classes. You might want to rethink your class structure. What exactly are you trying to use this for?)
To reduce coupling between the objects, you shouldn't let B have a reference to A - you should give it a reference to an interface implemented by A. The difference is subtle, but it really makes you think about what actions or data really need to be shared across the interface boundary.

Categories

Resources