Super class valiable value over sublclass variable with the same declaration - global-variables

Hello I found a question like this. The final answer printed by the main method is 3. But what I feel is the answer should be 13. When the new Bar() object is created, its constructor is called. the super() first line, would call back the Super method's constructor and assign a as 3. When call returns back to Bar() constructor "a" will be assigned to 8. Then after invoking addFive() this.a will be 13. So finally at the print statement by using the object Bar() referenced by n, calls a. Isn't it should be 13. How did the super calss "a" value print? please someone help me to sort it out.
public class _416 {
public int a;
public _416(){
a=3;
}
public void addFive(){
a+=5;
}
}
class Bar extends _416{
public int a;
public Bar(){
a=8;
}
public void addFive(){
this.a+=5;
}
public static void main(String[] args) {
_416 n=new Bar();
n.addFive();
System.out.println("Value="+n.a);
}
}

Variables are not polymorphic in java, your methods are polymorphic, so when you access a variable it is statically linked.
Thus your code n.a is statically linked with the a instance variable of _416 class as the reference n is of type _416
So when you call n.addFive(); it actually call the method of Bar (polymorphism). And in this method you add the 5 to the instance variable of Bar class and becomes 13 on the other hand instance variable of _416 remains intact which is 3.
Thus when you execute System.out.println("Value="+n.a); it prints the value of instance variable of _416 which is 3
Edit
Statically linked mean that your compiler resolves your ivar/methods at compile time and dynamically linked means that your compiler defers the linking for run time. That's the brief idea for more you can read this thread on stack

Because both superclass and subclass have a field called a, you've got two fields called a but field from superclass is hidden.
Let's see what happens in your code:
_416 n=new Bar();
Above code creates an instance of Bar class. But, since Bar is a subclass of _416, The constructor of _416 is called, which initializes field a from _416 class. After this, constructor of Bar is called, which initializes field a from Bar. then you 've got actually two fields:
n from _416 = 3
n from Bar = 8
Then, when this code is executed:
n.addFive();
It calls overriden method addFive() from Bar class. This method increases value of a from _416 class. So, you've got:
n from _416 = 3
n from Bar = 13
And, when, you are using field n.a here:
System.out.println("Value="+n.a);
, you are using field from Bar class. That's why printed value is 3.

Related

Find out from an object as an interface whose instance it is

I have the following scenario (https://run.dlang.io/is/19OOW9):
import std.stdio;
void main(string[] args)
{
inter1 c1 = new foo();
foo c2 = new foo();
writeln("Origin=interface: ", typeof(c1).stringof);
writeln("Origin=class: ", typeof(c2).stringof);
}
interface inter1 {
}
class foo : inter1 {
}
I work with interfaces and have different implementations for them. Now I need to know which concrete implementation is currently being used. So in the example above, I would like to know from c1 that it is an instance of the class foo.
Is this possible in the language D?
I have already tried the possibilities of object (e.g. TypeInfo_Class) and std.traits. Unfortunately without success.
A workaround is, of course, to provide the interface with a suitable meta method (https://run.dlang.io/is/Xnt0TO):
import std.stdio;
void main(string[] args)
{
inter1 c1 = new foo();
foo c2 = new foo();
writeln("Origin=interface: ", c1.strategyName);
writeln("Origin=class: ", c2.strategyName);
}
interface inter1 {
#property string strategyName() const;
}
class foo : inter1 {
#property string strategyName() const {
return "foo";
}
}
However, this is cumbersome and unusual for D. I can well imagine that there is a better implementation of this.
Best regards
Thorsten
It is quite simple actually: first cast to Object, then fetch the typeid, after a null check:
Object o = cast(Object) your_object;
if(o is null) { /* i don't think this ever happens but you should check anyway */ }
writeln(typeid(o)); // will tell the class name
If you want to call a method on a specific class, you can just cast directly to your class, and again, null check it.
The intermediate cast to Object allows the typeid (aka classinfo) to succeed, whereas calling it directly on an interface always returns the typeid of the interface itself. This is because a D interface is defined to be very thin for maximum compatibility with other languages and doesn't automatically assume run time type information is actually present through it. But the cast to Object tells it you are assuming the RTTI is present, and then typeid will pull it.
Note that the typeid data doesn't provide a whole lot of information... it is mostly just what's needed for dynamic cast, comparison, and other features of the language runtime. But one convenience method it has is a class name and toString methods, which is why the writeln succeeds. But if you're looking for more detailed runtime reflection, you'll have to do it with a CT bridge function, or probably better yet, just write your own methods in the interface.
But if all you need is the class name, use that toString. It gives the fully-qualified name, including module name, so instead of foo, you will get like yourmodule.foo. You can just cut that off if you like by slicing at the dot.

Run dynamic class based on field value

I have 3 classes each with a method which run some calculation and write the values in different fields, this method also writes the classname into a field from where the method runs from.
This works fine.
I recently created a button to re-run the method, from the class the method originally run from.
For example:
Class1 RunMethod
Class2 RunMethod
Class3 RunMethod
I am now creating the method for the action button when clicked, but I have no clue how to run a specific method from the class where it originally ran from. The class name is in a field.
I think I can accomplish this with SysDictClass, but I have no clue how to start, how can I best start with this method?
This should get you the idea. I wrote it in AX 2009 but it should probably work in AX 2012 as well.
public static client void SysDictClassJob()
{
ClassId classId;
Object obj;
SysDictClass sysDictClass;
;
// Create instance (if you are going to call a member method)
classId = className2Id('SomeClass');
obj = classFactory.createClass(classId);
// Invoke member method
sysDictClass = new SysDictClass(classId);
sysDictClass.callObject('yourMemberMethod', obj);
// Invoke static method
sysDictClass.callStatic('yourStaticMethod');
}

Variable is not of the type class

I have a custom class for holding a collection of data.
I use this class throughout my code, and it works without a hitch, except for in one place, when I need to pass the class object to a method. Here is some very basic code to demonstrate what I am seeing.
public class doSomething
static void myMethod(customClass_myItem) {}
public class customClass
public str classMethod() {}
form method
customClass myItem = new customClass();
myItem.classMethod(); //this works, so I know the class is good
doSomething::myMethod(myItem); //Gives error: variable is not of the type CLASS.
I am completely lost here. If I couldn't use the class at all, I would understand, but with it not working when passed to another method.. doesn't make any sense. If I put in a breakpoint, the debugger indicates myItem is a class of the correct type.
Any suggestions?
Thanks
Your myMethod expects an object of class customClass_myItem (or a descendant) not customClass.
If you change your parameter type to object it should work.
static void myMethod(Object o) {}

How can I get the name of the defined class in a parent static method in Groovy

Note: I found another answer that suggests that Java would redirect the static method call to it's own class even if it's called on a child class so I guess I need to find a Groovy work-around trick or it's just not going to be doable.
Here's the problem: I created an abstract generic "Launcher" class with a "public static void main". The idea is that you extend it and in your child class you annotate methods like this:
#Command("Show an explorere shell")
public dir() {
"explorer".execute()
}
The parent of this class has a main that goes through, reflects for the #Command annotation and if the method name matches your parameter, executes it.
The problem is that I can't figure out how to tell what the actual, instantiated class is within the parent's static main method.
I'm pretty sure there is a trick somewhere--"this" won't work in statics, stack traces don't contain the actual class, just the parent class, and I can't find any meta-info in the class or MetaClass objects that helps.
Currently I've gotten it to work by hard-coding the name of the child class into the parent's main like this:
public class QuickCli {
public static void main(String[] args} {
(new HardCodedChildClassName())."${args[0]}"()
}
}
I cut quite a bit out of that, but it's the general idea. I'd like to replace
"new HardCodedChildClassName()"
with something that will work for any class that extends this class.
Given the two code snips above, the command would be executed from the command line as:
groovy HardCodedChildClassName dir
Although I'd prefer not to make all the #Command methods static I could do so if I had to, but currently I'm not even convinced I could make that work.
I'm not sure that's possible. In any case, it's likely to be an ugly hack if it is. I'd suggest this alternative: Rather than using the static main() entry point, make QuickCli a Runnable. Groovy will automatically create an instance and call run() on it when it is launched.
One minor problem here is capturing the command-line arguments. Groovy handles this by passing them to a constructor with a String[] parameter. The instantiated class needs this constructor to capture the args, but in Java, constructors are not inherited. Fortunately, Groovy has an InheritConstructors annotation that works around this.
Here's an example of how this would look:
class QuickCli implements Runnable {
def args
QuickCli(String[] args) {
this.args = args
}
void run() {
"${args[0]}"()
}
}
#groovy.transform.InheritConstructors
class HardCodedChildClassName extends QuickCli {
#Command("Show an explorere shell")
public dir() {
"explorer".execute()
}
}

ActionScript 3 constructor scope question

out of curiosity I decided to experiment with the following in a Flex 4 project:
public class MyGroup extends Group
{
public function MyGroup()
{
super();
var myLabel:Label = new Label();
myLabel.id = "myLabel";
myLabel.text = "My label!";
this.addElement(myLabel);
} etc.
This custom component does what I'd expect; it looks like a label control with text="My label!".
Question: is there any way to reference the myLabel label control (e.g. to change the text) elsewhere in the project?
At the moment the only way I can get to the inner label control is by calling something like myGroup.getElementAt(0).
I realize that it would make more sense to have the label be a class variable -- I'm just wondering how this code works.
You can make a public setter to change you text label:
public class MyGroup extends Group
{
private var _label:Label=new Label();
public function set label(value:String):void{
_label.text=value;
}
public function MyGroup()
{
super();
_label.id = "myLabel";
label = "My label!";
addElement(_label);
}
.....
}
var myGroup:MyGroup=..
myGroup.label="Hello";
In your case since you are declaring your var myLabel inside a function, it 's scope will only apply inside this function
In ActionScript, variables are named handles that you can pull on to get objects and data. Variables have something called scope, which specifies in what parts of the code the handle is valid.
When you create a variable inside a function, its scope is that function. That is, that particular named handle is only usable inside that function.
In your code, you create a handle called myLabel, and put a Label in it--let's call it Label123. Next you put Label123 into the element list of MyGroup, which gives MyGroup a handle attached to Label123. Then the function ends, and the handle called myLabel is no longer usable. Label123 still exists, because MyGroup has a handle to it.
If you create myLabel as a private or protected class variable, that handle will be usable from any function inside MyGroup. If you create it as a public class variable, it will be usable anywhere inside MyGroup, and also anywhere in the code you have an instance of MyGroup. (And if you create it as an internal class variable, it will be usable anywhere inside the package MyGroup is in.)

Resources