Can you access sub class variable via super class in Java - 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).

Related

Changing object type in runtime using reflection

Is it possible to change the object type in runtime using reflection?
Let's say I have an instance of an object A. Objects of type B extend A. Would it be possible to change the object type of the instance of A into B so I can safely make a cast of A into B?
Maybe by changing the final attribute .class or a similar trick?
No, it is not possible.
Reflection that you mentioned allows discovering given class at runtime (i.e. finding method, field etc by name) and accessing methods and fields of objects at runtime without compiling the client code against specific class. For example you can invoke method foo() of any class.
Changing type of object actually does not make sense for me at all. Object contains is an instance of speicific class that have both data and methods. I can somehow imagine way to change the memory allocated for object at runtime using sun.misc.Unsafe, however I even cannot imagine how can you change the implementation of methods done in specific class associated with the object.
And the question that still remains here: why? Could you probably explain your task and ask for solution proposal?
EDIT
Following the new information posted by OP as a comment to my answer I'd like to add the following.
As far as I understand the situation is the following.
There is a third party library that implements class A and AFactory. OP uses code like the following:
A a = AFactory.create();
However he does not need A. He needs B extends A that implements additional functionality.
Possible solution is the following.
Create class B extends A:
public class B extends A {
private final A a;
public B(A a) {this.a = a;}
// delegate all methods of A, i.e.:
#Override
public boolean isA() {return a.isA()}
// add your functionality, e.g.
public boolean isC() {/* your code here*/}
}
Now use this class as following:
A a = AFactory.create();
B b = new B(a);
Now your can use all functionality of A via B and the additional functionality as well.

Regarding extending of classes [duplicate]

This question already has answers here:
Java doesn't support multiple inheritance but implicitly every class in java extends Object and allows one more [duplicate]
(8 answers)
Closed 10 years ago.
I have a query in java, that since Object class is the parent class for all, I want to know that is Object class is being implicitly extended by every class in java.
For example: if I make an object class B then I extend class A that is ok since in java, class can extend only a single class at most, but since my class B has implicitly extended the Object class then how can it extend class A? Please advise.
Only when a parent is not specified does it implicitly inherit off of Object, otherwise it only inherits off of the specified parent.
Side note:
This is allowed:
C
|
A
|
B
In the above case, replace C with Object to be in line with what you're asking.
This is not allowed:
C A
\ /
B
The inheritance can be as deep as you want it to be, but one object cannot have multiple parents.
Think of it as a family tree where individuals only have one parent. Each individual only has one parent, but all that parent's ancestors are also ancestors of the individual. That's what's meant when it is said that all classes extend Object: it is the most remote ancestor of all, though only the direct ancestor (parent) of those classes that are declared with extends Object or with no extends declaration at all.
I think you know the concept but you must be a bit confused. Think of a tree. Object class is the root of that tree. It has leaves and other nodes in between. No matter how your class hierarchy is designed, it will eventually an Object because its root is that. So you can extend any class (not abstract or Interface), without thinking of Object class. Because Object extention will be done automatically for you.
Here, I will suggest, the keyword is EXPLICIT. You can EXPLICITLY extend only one class. But if you don't do that Java will implicitly extend your class with Object class. If you have done that Object must be somewhere up in the hierarchy of the inherited class.

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.

Identical classes casting?

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

Uninstantiated Anonymous Classes in Java

It's been about 6 years since I've written Java, so please excuse the rust.
I'm working with a library method that requires that I pass it Class objects. Since I'll have to invoke this method a dynamic number of times, each time with a slightly different Class argument, I wanted to pass it an anonymous class.
However, all the documentation/tutorials I've been able to find so far only talk about instantiating anonymous classes, e.g.:
new className(optional argument list){classBody}
new interfaceName(){classBody}
Can I define an anonymous class without instantiating it? Or, perhaps more clearly, can I create a Class object for an anonymous class?
Unfortunately, there's no way you can dodge the instantiation here. You can make it a no-op, however:
foo((new Object() { ... }).getClass());
Of course, this might not be an option if you have to derive from some class that performs some actions in constructor.
EDIT
Your question also says that you want to call foo "each time with a slightly different Class argument". The above won't do it, because there will still be a single anonymous inner class definition, even if you put the new-expression in a loop. So it's not really going to buy you anything compared to named class definition. In particular, if you're trying to do it to capture values of some local variables, the new instance of your anonymous class that foo will create using the Class object passed to it will not have them captured.
short answer
you cannot (using only JDK classes)
long answer
give it a try:
public interface Constant {
int value();
}
public static Class<? extends Constant> classBuilder(final int value) {
return new Constant() {
#Override
public int value() {
return value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}.getClass();
}
let's creating two new class "parametric" classes:
Class<? extends Constant> oneClass = createConstantClass(1);
Class<? extends Constant> twoClass = createConstantClass(2);
however you cannot instantiate this classes:
Constant one = oneClass.newInstance(); // <--- throws InstantiationException
Constant two = twoClass.newInstance(); // <--- ditto
it will fail at runtime since there is only one instance for every anonymous class.
However you can build dynamic classes at runtime using bytecode manipulation libraries such ASM. Another approach is using dynamic proxies, but this approach as the drawback that you can proxy only interface methods (so you need a Java interface).
You can only reference an anonymous class ONCE. If you do not instantiate it there, you cannot instantiate it since you do not have a name for it.
Hence I believe that anonymous classes can only be used in conjunction with a "new BaseClass()".
In your situation you would pass a BaseClass object to your method doing the work, and instantiate the anonymous object in the source code when you need the object to pass.
You can't access the Class object of an anonymous class without instatiating it. However, if you only need access to the class, you could define local classes within your method and refer to these using the ClassName.class literal syntax.
You can assume the name of an anonymous class and call Class.forName("mypackage.MyBaseClass$1") to get a handle to an anonymous class. This will give you the first anonymous class defined in your MyBaseClass, so this is a rather fragile way to refer to a class.
I suspect whatever you are trying to do could be done a better way. What are you really trying to achieve? Perhaps we can suggest a way which doesn't require you to pass a Class this way.
You can access the class object of an anonymous class by calling .getClass() on it immediately after creation. But what good would that do?
I think the key is in this part of what you said:
I'm working with a library method that requires that I pass it Class
objects.
Why does it want you to pass it Class objects? What does this library do with the Class objects you pass it? Instantiate objects? But if so, what constructor does it use and how does it decide what arguments to pass? I don't know what library you are using or what it does, but I would guess that it always creates objects using the no-argument constructor. However, that will not work for anonymous classes anyway, since they have no public constructor (and in any case, to instantiate any non-static inner class, a reference to the outer instance must be provided, so there is no no-argument constructor).

Categories

Resources