Does parent class method use hidden variables [duplicate] - java

This question already has answers here:
Hiding Fields in Java Inheritance
(2 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a parent class A which has a primitive type property x
public class A {
String type = "A";
int x = 5 ;
void increment()
{
x++ ;
System.out.println(x);
}
}
I have a child class B which extends from class A, This child class also has propery x of String type
public class B extends A {
String type = "B" ;
String x = "Hello";
}
Now, both parent and child class has instance variable x with different type( int and String).
Parent class A has a method to increase value of X and now the method is available in the child class B ( Class B extends Class A, so all the methods in class A are accessible in class B)
Now I have a main method in a Runner class,
public class Runnable {
public static void main(String[] args)
{
//Creating object
B instanceOfB = new B() ;
//Invoke increment method
instanceOfB.increment();
}
}
While running the main method, I got an OUTPUT : 6
I am invoking increment method using reference variable instanceOfB
instanceOfB.increment();
instanceOfB is an instance of Class B.
By invoking this function, we are trying to increase the value stored in variable x, but x has reference to a String Object.
It should either throws compile time reception or run time exception because we are trying to increase a String object, It is not possible but I got output 6.

The behavior of instance variables and instance methods in a class hierarchy is different. If you wanted to access the value in the subclass from the superclass, you would need to wrap the subclass value with an instance method that is declared in the superclass but overridden in the subclass.

Related

Get variable from child class variable stored in parent class variable [duplicate]

This question already has answers here:
why can not access child fields using parent reference
(6 answers)
Closed 4 years ago.
How to access child class variables? Is it necessary to convert object?
public class A {
int first;
}
public class B extends A{
int second;
}
public void doTheMagic(){
B variableB = new B();
A variableA = variableB;
variableA.second; //-> second is unknown;
}
While you can assign varibaleB to type A (since B inherits from A), A does not have a class member called second.
Of course, you know that it is of type B, so you can cast it:
B variableB = new B();
A variableA = variableB;
((B)variableA).second;
To clarify: You can only access the class members of the concrete type, not its subclasses.

how java constructor does work? [duplicate]

This question already has answers here:
Does polymorphism apply on class attributes in Java?
(8 answers)
Closed 4 years ago.
I have the following program :
class A{
int b = 50;
}
class B extends A{
int b = 20;
}
public class Maini{
public static void main(String[] args){
A a = new B();
System.out.println(a.b);
}
}
and the result is 50 and I would like to know why?
before I run the code I am pretty sure that the result should be 20.
This has nothing to do with how constructors work.
Note that the member variable b in class B does not override the member variable b in class A. Only non-static, non-private methods can be overridden. Member variables cannot be overridden.
If you have an instance of class B, then it actually has two member variables called b: one in the superclass (A) part of the object, and one in the subclass part (B).
The reason that you see the value 50, which is the value of b in the A part of the object, is because the variable a in the main method is of type A. If you change this to B, you'll get 20:
B a = new B(); // instead of A a = ...;
In the statement
A a = new B();
You are calling Bs constructor in an object of type A
In your program, you have given no constructor to B, so it looks to A.
In A, the value of int b is 50 and an object is of type A, hence the value is chosen as 50
If you had a constructor in B e.g.
B() { b = 20;}
the value would be 20.
You think that you are creating a B but you have not written any constrcutors for the class B so it looks to the super() constructor which is it's parents (A). So you now have an object of A. If you are curious about why A's object isi being created while there is no constructor to it too. A calls to it's super constructor too which is Java's Object Class's constructor.
I hope that I could make this point clear.
use a intellitrace enabled IDE for better experience of coding.
1st of all you'l hav a default constructor if you are not imposing on it.
Secondly you are defining an object of type 'A' not 'B'. if you want the output as 20 then you hav to include this B() {int b = 20;}.
Here in this code Sniplet there is no constructor in Any class.
So JVM will create no argument default constructor in all classes.
While you are Running this then .
In the below code you
a is referring class A and having object of class B
A a = new B();
So here the Object a will have class A 's variable value.
and Class B object value as its calling Class B 's default constructor(new B();)
If Class A and B have same Method like below Example:
class A{
int b = 50;
void method(){
System.out.println("Method of A class");
}
}
class B extends A{
int b = 20;
void method(){
System.out.println("Method of B class");
}
}
public class Maini{
public static void main(String[] args){
A a = new B();
System.out.println(a.b);
a.method();
}
}
Then a.method() will print
50
Method of B class
as a is have Class B 's object.
When you write A a = new B() the object a is type A. This is why you're getting b = 50. If you want to get b = 20, you need to declare a as a B class
Hope it's clear enough.
Best

Inheritance issue : Results are different on creating same class object [duplicate]

This question already has answers here:
Does polymorphism apply on class attributes in Java?
(8 answers)
Closed 5 years ago.
Case 1:
In the below example if i call a.i it is printing 10 as answer. But A a = new B(); isn"t this like object of b is getting created so value 20 should be printed instead of 10.
class A
{
int i = 10;
}
class B extends A
{
int i = 20;
}
public class MainClass
{
public static void main(String[] args)
{
A a = new B();
System.out.println(a.i);
}
}
Case 2:
Also if i create the same program as above using methods inside classes instead of printing variable values as in above case then result is different :
class A{
void test(){
System.out.println("hi");
}
}
class B extends A{
void test(){
System.out.println("hello");
}
}
public class Test {
public static void main(String[] args) {
A a=new B();
System.out.println(a.test);
}
Now in this case hi is printed instead of hello , so why is the behavior different when i try to print variable value and when using methods? Overiding happens between the methods only and not with variables?
Because what you have in the first example has nothing to do with polymorphism as fields read are not dynamically dispatched.
What you have however is a name shadowing, so i in the statement A.i refers to the field declared in A and B.i is invisible at this point.
In Java only methods can be overriden, not instance variables.
When you declare a field with the same name as an existing field in a superclass, the new field hides the existing field. The existing field from the superclass is still present in the subclass, and can even be used
Check these -
Java Tutorial - Hiding Fields
JLS Example - Hiding of instance fields

Difference between super and this in the commands below?

What is the difference between these commands when I have a class A and a Class B where B extends A , and they have a common instance variable size and the commands below are called from a method printSize1 inside B?
class A {
protected int size;
}
class B extends A {
protected int size=7;
public void printSize1() {
System.out.println(((A)this).size)
System.out.println(super.size);
}
}
Also I have the same question with these two. I have a class A and a class B where B extends A, and they both have a method with the same name printSize and an instance variable size and the below commands are called from a method printSize2 inside class B.
class A {
protected int size;
public void printSize() {
System.out.println("Size=" + size);
}
}
class B extends A {
protected int size=7;
public void printSize2 {
((A) this).printSize();
super.printSize();
}
public void printSize() {
System.out.println ("MSize="+size);
}
}
i have a class A and a Class B where B extends A which they have a common instance variable size
No, they don't. They have separate instance variables called size. One is in the part of the object associated with A, and the other is in the part of the object associated with B. Let's call them A$size and B$size. For them to have a common instance variable, you'd remove the declaration of size from B so they're both using A$size.
Redeclaring an ancestor's non-private instance variable (field) is always a bad idea, because it leads to this sort of confusion.
Both of the below output 0 for your example code, because they're both accessing A$size, which you never assign a value to, so it has the default value 0:
System.out.println(((A)this).size); // 0
System.out.println(super.size); // 0
So the question is: Why are they both using A$size and not B$size? Because of the type of the reference we're using to look up size. In both cases, the type of the reference is A, because the type of (A)this is A (via cast) and the type of super in a method in B is also A. Since the type of the reference is A, it's A's size that gets used.
In this particular case there isn't much of a difference between the two, but there would be if you added another layer to the hierarchy:
class A {
protected int size = 1;
}
class B extends A {
protected int size = 2;
}
class C extends B {
protected int size = 3;
void printSize() {
System.out.println(((A)this).size); // 1
System.out.println(super.size); // 2
System.out.println(this.size); // 3
}
}
Moral of the story: Don't redeclare instance variables declared by an ancestor (unless the ancestor's version is private).
Note that this is different for variables than it is for methods. Instance methods are polymorphic. Instance variables are not. With methods, you get the method associated with the final type of the object (unless you use super or a qualified super, because those are special and bypass polymorphism).
This is what's coming into play in your second example in printSize2. Because methods are polymorphic, it doesn't matter that you've cast this to be type A in ((A)this).printSize(), you still get B's printSize. But super.printSize() is special because super is special and bypasses polymorphism, giving B access to A's printSize.

Why is the output of this program i=10? [duplicate]

This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Closed 6 years ago.
class A
{
protected int i=10;
}
class B extends A
{
protected int i=15;
}
public class Test extends B
{
public static void main(String a[])
{
A obj=new Test();
System.out.print("i="+obj.i);
}
}
It's output is i=10, but how?
How is the memory allocation for the object will take place.
A obj=new Test();
Means, you are accessing the members of Class A and executing the methods of Test(polymorphism).
I suggest you to read the official docs on inheritance and polymorphism to understand deep.
Polymorphism is linked to objects not references. Since you are using a reference of type A, you will get A.i if you have method getI() in A and override it in B, then call obj.getI(), then you will get B.i's value
In java, Variable Overriding is not there. We have the concept of method Overriding.
In your code
A obj=new Test();
You can able to access members of A. If you have overridden same method in both the classes (Parent and Child). And you are calling that method with obj. This time you will get output from Child class overridden method. this is the concept of Polymorphism.
Line 1: A a = new A();
the method existence will be checked in A class and the method will be called from A class also.
a.g();//A class method will be called
System.out.print("i="+a.i);//A class i will be accessed
Line 2: A b = new B();
the method existence will be checked in A class and the method will be called from B class.
b.g();//B class method will be called and it will also check that it is` available in A also or not if not then compile time error.
System.out.print("i="+b.i);//A class i will be accessed

Categories

Resources