Assign parent 's instance variable by using super keyword in Java - java

I have 2 class in Java
1. public class A {
2. public int i = 1;
3. }
4.
5. public class B extends A {
6. int i = 2;
7. public void print() {
8. super.i = 3;
9. A obj = new B();
10. System.out.println(obj.i);
11. System.out.println(this.i);
12. System.out.println(super.i);
13. }
14.
15. public static void main(String [] args) {
16. new B().print();
17. }
18.}
When I run above code it print
1
2
3
So I want to know why line 10 and 12 print different output? I think because I assign super.i = 3 and create new object of A, the result should be 3, 2, 3. Please help me

There are two B objects in your program, the one created by main(), and the one created by the print() method in that first object.
Each B has its own instance of i.
Only the first B has i set to 3, and obj refers to the second B.

Related

Sequence of digits to be printed_Need help on why '2' becomes third in order

class A{
public A() { }
public A(int i) { System.out.println(i ); }
}
class B{
static A s1 = new A(1);
A a = new A(2);
public static void main(String[] args){
B b = new B();
A a = new A(3);
}
static A s2 = new A(4);
}
Ouput -> 1 4 2 3
Query -> First two numbers displayed in order of being static class initialisation
But have a query on what basic '2' gets printed. Could see the statement 'A a = new A(2);' which is declared as field for class B and not inside main method.
Could somebody help on how the third number '2' got the next priority after static variable.
You have two static initialisers in class B, so when that class is ran, those two will be executed first in order, so static A s1 = new A(1); will print out 1 and then static A s2 = new A(4); will print 4. Then the code within your main method will start to execute. The first line in your main method is B b = new B();. This creates a new object of class B and in doing so will call A a = new A(2); which will cause 2 to be printed to the console. Then you call A a = new A(3); which prints 3 to the console. And there you have it and output of
1
4
2
3

Instance looking up field / weird behaviour with variable assignment

I'm exploring method and variable inheritance in Java and specifically how instances of a class looks up fields (static variables).
However, I wasn't able to get the behaviour I expected in the Java fragment below.
More puzzlingly, running the same (?) thing written in Python gets me the expected results.
class Up {
public static int n = 1;
public int m;
public void setter() {
System.out.println("I looked up " + this.n);
this.m = this.n;
System.out.println(this.m);
}
}
class Sub extends Up {
public static int n = 6;
public int m = 5;
public Sub() {
super();
}
}
class Run {
public static void main(String[] args) {
Sub foo = new Sub();
foo.setter();
System.out.println(foo.m);
}
}
class Up:
n = 1
def setter(self):
print("I looked up", self.n)
self.m = self.n
print(self.m)
class Sub(Up):
n = 6
m = 5
foo = Sub()
foo.setter()
print(foo.m)
The Python code ran as expected and printed out:
I looked up 6
6
6
The equivalent Java code however, printed out:
I looked up 1
1
5
I guess I have two problems here:
Why did Java interpret this.n as the field initialised in class Up instead of the actual class of foo, Sub?
After successfully looking up 1, Java should've bound foo.m to 1. Printing out this.m seems to indicate that it had, but printing out foo.m directly from the main method indicates that it hadn't, why is this?
I suspected that this is caused by the fact that Java "accesses variables in run-time" (I'm still wrapping my head around that), which I guess explains number 1, but I'm hoping that someone would explain to me what's happening behind number 2?
AS for the second question, you have two instance variables called "m". One declared in Class Up, and one declared in class Sub that hides the variable in Up. So when you call setter(), which is a method of Up, it uses the value of m found in Up (Up know nothing about the variables found in any of its subclasses).
But when you later print foo.m, since foo is an instacnce of Sub, it uses the value of m found in Sub, which is still 5.
Remove the declaration of m in class Sub and see what happens.

Understanding class members behavior Polymorphism

I'm facing some difficulties while trying to understand, what actually happens when we initiate an instance of a child class.
public class A {
2. public int x, y;
3. public A () { x=1; y=2; }
4. public int getx () { return x; }
5. }
6. public class B extends A {
7. public int x, z;
8. public B () { super(); x=3; y=4; z=5; }
9. public int getx () { return x; }
10. public int getz () { return z; }
11. }
12. public class Prob1 {
13. public static void main (String[] args){
14. A o1 = new A();
15. A o2 = new B();
16. B o3 = new B();
17. System.out.println(o1.x);
18. System.out.println(o1.getx());
19. System.out.println(o1.y);
20. System.out.println(o1.getz());
21. System.out.println(o2.x);
22. System.out.println(o2.getx());
23. System.out.println(o2.y);
I would love to here a detailed explanation of what is going on here exactly, but the main thing I can't understand is why line '21' prints the number 1, and line '23' prints the number 4.
Polymorphism applies to methods, not to instance variables.
Both lines 21 and 23 print the value of the instance variables of class A, since that's the compile time type of o2 (even though its runtime type is B).
21. System.out.println(o2.x);
The value of A's x member is 1 (set by the constructor public A () { x=1; y=2; }).
23. System.out.println(o2.y);
The value of A's y member is 4 (set by the constructor public B () { super(); x=3; y=4; z=5; }).
Note the B has an x instance variable that hides A's variable of the same name. Therefore B's constructor doesn't change A's x variable to 3. On the other hand, B doesn't have a y instance variable, so y=4; changes the value of A's y variable to 4.
BTW, line 20 has a compilation error. I had to comment it out in order to execute your code.
Also note that o2.getx() gives a different result than o2.x, since getx() is a method overridden by class B, so it returns B's instance variable x, whose value is 3 (since the runtime type of o2 is B).

Understanding how variable point to value in Java

I have a below code. The variable c and d are class variables and initially they were pointing to value 0, but when I did c=a* a; and d =b* b*b they printed value as 25 and 64 which is correct. so what I think now is that the c and d are now pointing to value 25 and 64 and they are class variables, so if I do j=c+d; it should give me 89 as j value, but it is giving me 0... why? I know if I use static with c and d variable it will give me 89 value... but why I should use static as c and d are global variables and there values are now updated to 25 and 64. Please let me know. Thanks.
public class BaiscSum {
int a=5;
int b=4;
int c;
int d;
int j;
public void square() {
c=a*a;
System.out.println(c);
}
public void cube() {
d=b*b*b;
System.out.println(d);
}
public void sum() {
j=c+d;
System.out.println(j);
}
public static void main(String[] args) {
BaiscSum squ= new BaiscSum();
squ.square();
BaiscSum cub = new BaiscSum();
cub.cube();
BaiscSum su = new BaiscSum();
su.sum();
}
}
You are using three separate instances of your class. This means that squ, cub, and su each have their own version of the class. Instead, use the same one instance, so that all changes will happen to the same instance.
public static void main(String[] args) {
BaiscSum sum= new BaiscSum();
sum.square();
sum.cube();
sum.sum();
}
If I do j=c+d; it should give me 89 as j value, but it is giving me
0. why?
Because you are referencing sum() with su object but you have not called cube() and square() on su instead you called it with cub and squ respectively.
Change to
BaiscSum su = new BaiscSum();
su.square();
su.cube();
su.sum();
It will give you the expected output.
Since all the variables you are using are instace so every object will have its own set of variable on their respective memory spaces and if you changed any one objects variable it will not effects other objects value.
This could clear more
As an explanation every object is assigned a seperate memory and so changes to the variable of one objects doesn't effect changes to other objects variable unless they are static. So in the third object c and d is not initialized for su object so jvm uses default value if int ie 0 giving you a sum of zero.

Confusion in working with objects in Java. Why the program prints that value?

I need your knowledge to explain something very simple that confuses me
As you can see, it's a very beginning practice on Java, and I already face the first confusions.
So the question is, what is true from the A, B, C, D?
A. line 12 prints 4
B. line 13 prints 9
C. line 13 prints 18
D. line 14 prints 18
I know that the answers are C and D but because I'm studying and I try to understand why, could you please explain this to me?
I first thought that the correct ones whas A and B but it comes out that I was wrong.
What is really going on with ob.t = ob2; ob2.t = ob; and whats the role of Test t; in the Class Test?
1 class Test {
2 Test t;
3 static int a;
4 Test(int i) { a = i; }
5 void xchange(Test ob, int i) { ob.a = i * ob.a; }
6 }
7 class Call {
8 public static void main(String args[]) {
9 Test ob = new Test(2); Test ob2 = new Test(3);
10 ob.t = ob2; ob2.t = ob;
11 ob.xchange(ob, 2); ob2.xchange(ob.t, 3);
12 System.out.println(ob.a);
13 System.out.println(ob2.a);
14 System.out.println(ob.t.a);
15 }
16 }
What's the role of Test t; in class Test?
It declares a field in Test of type "reference to Test". Note that variables and fields in Java cannot store objects; they can only store references to objects.
What is really going on with ob.t=ob2; ob2.t=ob;?
It sets the t fields of both Test objects to contain references to each other. So the first object's t field contains a reference to the second object, and vice versa.
It is tempting to say that "it assigns ob's t field to contain a reference to ob2", but strictly speaking this is incorrect, as ob and ob2 are not objects.

Categories