Inheritance referring instance variables [duplicate] - java

This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Closed 5 years ago.
class A{
int x= 30;
void printA(){
Sysout(x);
}
}
class B extends A{
int x= 40;
}
class MyMain(){
public static void main(String args[]){
B obj = new B();
obj.printA(){
}
}
B is the child class of A.
Why the output is coming t be 30?? It should b 40? Object of B should have value of x as 40. And sysout(x) means this.x

You are calling the print that refers to A.x and not to B.x. You should try to override printA in B

Even though you are calling the method using B, it is executing method from A as it have access. And you are using the variable from class A in that method.
And sysout(x) means this.x
Yes, in your case, this means A as you not overridden that method.

Related

Does parent class method use hidden variables [duplicate]

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.

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

confused in Inheritance, could anyone help me? [duplicate]

This question already has answers here:
Java Inheritance - instance variables overriding
(3 answers)
Closed 8 years ago.
Code in Java
public class A {
int x;
public A() {
x = 0;
}
public void print() {
System.out.println("This is A");
}
}
public class B extends A {
int x;
public B() {
x = 1;
}
public void print() {
System.out.println("This is B");
}
}
B b = new B();
A a = b;
System.out.print(a.x);---------------->0
a.print();---------------->This is B
I am very confused. I create object b for B class, although I assign b to a, I think b should still point the class B. Why the "a.x" will return 0 instead of 1? Why a.x point to the x in A, but a.print() point to the print() method in B?
fields are not polymorphic but the methods are,
which means method will be invoked on the object which is referred by reference at runtime
field variables are tied to reference, so if you remove field x from class A and try the same code it will fail to compile
You are seeing some irregularities on how polymorphism is applied in Java. Polymorphism is seen where invoking a.print() invokes B's print(), while this is not the case for fields. The field is tied to the reference, so in this case b.x and a.x are distinct (although you could leave out x in B's definition and have a single field declared in the superclass. In that case, a form of hiding is seen.

Categories

Resources