Why is this program printing 25? (Java inheritance) - java

In this program
class a
{
int a=25;
public void aa()
{
System.out.println(a);
}
}
class b extends a
{
int a=2;
public static void main(String[] args) {
b x=new b();
x.aa();
}
}
why does "x.aa()" prints 25 ans why not 2?,what is the reason behind it?
class a
{
int a=25;
public void aa()
{
System.out.println(a);
b();
}
public void b()
{
System.out.println("this should print");
}
}
class b extends a
{
int a=2;
public static void main(String[] args) {
b x=new b();
x.aa();
}
public void b()
{
System.out.println("this should not print");
}
}
and if we consider the above output,then here again the output of b() of above should print "this should print" but we are getting the ouput from sublcass "this should not print"

Class b inherits class A, so when you call x.aa, it is calling method aa of class a. The member a of class a is initialized with 25 so it prints 25. Class a does not know about the member a of class b.

Fields cannot be overridden, and are not virtual. B.a* is independent of A.a, to the point that they can actually have different types. There is no way for B to make A aware of B.a in place of A.a. Instances of B will actually have two fields named a, but one is hidden ("shadowed") by the other. (If desired, code B can refer to its A.a field by writing ((A)this).a. This is because the appropriate a is selected based on the type of ((A)this), which is A, rather than the runtime type of the instance, which would be B or a subtype of B.)
* Note: I have renamed your classes to A and B: per the Java naming conventions, class-names begin with uppercase letters.

b x=new b();
while you will do this this will print out put of the constructor as its giving because its clearly making the object of b class and while in the case of class A in that class that b() act as the method so it wont call when you are making object of class b.
while in the case of
b x=new b();
x.aa();
this it will by default call the inheritance and will print as u getting output.
and one more thing.
public void aa()
{
System.out.println(a);
}
in the case of this it will use the local variable of that particular class so it will print whatever you have defined on that class. in your case that is a=25;
by the way nice question.

method aa() is member of class a. so, method aa() can see/access instance member of class a.
Now, you have inherited class a to b. it means object of class b can access/call aa(). but, it doesn't mean that aa() is allowed to access variable a of class b. thats why method aa() is printing the variable a of it's own class and prints 25.
now about your second program. in class b, you are overriding method b(). while calling an overridden method, the selection of method(whether from sub class or super class) is done on the basis of instance of a invoking object(whether sub class or super class respectively).
you have called method aa() with the instance of class b that is why method b() of class b is called.

Related

What happend will subClass and SuperClass have same attributes in Java?

public class Test {
public static void main(String[] args) {
B b = new B();
b.test();
}
}
class A {
String aString = "a";
void test() {
System.out.println(aString);
}
}
class B extends A {
String aString = "b";
}
why the cant input out "b"?
i just think b.test() will call method of superClass, so b will user superClass's attribute.
why the cant input out "b"? i just think b.test() will call method of superClass, so b will user superClass's attribute.
Java class and instance variables can be inherited, but they are not virtual. That is, all variable identifiers appearing in Java code are resolved at compile time -- there is no dynamic resolution for them.
Thus, the appearance of identifier aString in method A.test() is resolved at compile time to the aString attribute of class A. This is the attribute that all invocations of that method will access, regardless of the actual class of the object on which it is invoked. If you want to use the attribute of class B when test() is invoked on an instance of that class then provide getter methods in classes A and B and have A.test() obtain the string via those.
The variable in b is hiding the variable in a. You can fix it by removing the type in b
class B extends A {
public B () {
aString = "b";
}
}
class A {
String aString = "a";
void test() {
System.out.println(aString);
}
}
class B extends A {
String aString = "b";
}
Creates 2 aString variables for B. While A will not know about B extending it, B can always access "things" from its parent class A, using the super keyword. So when you are in B, you can use aString and super.aString and they will refer the 2 different variables:
class Ideone {
public static void main (String[] args) {
A a=new A();
B b=new B();
a.test();
b.test();
b.suptest();
}
static class A {
String aString="A.aString set from A";
void test() {
System.out.println("A.test(): "+aString);
}
}
static class B extends A {
String aString="B.aString set from B";
{
super.aString="A.aString set from B";
}
void test() {
System.out.println("B.test(): "+aString);
}
void suptest() {
System.out.print("B.suptest() calling super.test(): ");
super.test();
}
}
}
You can try it on IdeOne, produces output
A.test(): A.aString set from A
B.test(): B.aString set from B
B.suptest() calling super.test(): A.test(): A.aString set from B
Where the first two lines show nothing fancy, A.aString and B.aString both contain their initial value.
But the third output line shows that super.test() call in B really "ends" in A.test(), and that the initializer block in B really altered the inherited aString field.
(Side note: the static class magic relates to the example being contained in a single file, it doesn't affect the inheritance-part)
You are correct.
Since Class A and the method test() are not abstract and the fact that the method test() was not overrided by its subClass B, the return will be exactly how was specified in Class A even if you call it from a B instance.

Java IS-A relationship with method override

public class A {
public void m1() {
System.out.println("A m1");
}
}
public class B extends A {
public void m1() {
System.out.println("B m1");
}
public void m2() {
System.out.println("B m2");
}
}
public class Result {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*A a = new A();
a.m1();
B b = new B();
b.m1();
b.m2();
*/
A ab = new B();
ab.m1();
}
}
In the above code, I have a Class A and Class B that extends Class A. In class C I am creating the object of class B and it's been assigned to class A. when I try to call ab.m1() it calling the method in class B.but when I try to call ab.m2() i get compile time error. I am not understanding why class B method is called during ab.m1(). can someone help me in understanding the concept much better.thanks in advance.
A ab = new B();
You create a reference of type A and point it to an object of type B. This is valid and legal because B extends A, so an object of type B IS-A type A. That's why, when you call ab.m1(); you're calling the method defined in B. Your object type is B, so it overrides the method defined in A.
However, you can't call ab.m2() because the reference is type A, and knows nothing about new methods defined in B that weren't included in A. The reference only has access to the things defined in A (and anything that it might inherit from its super types, like Object).
B -->A// B is-a A
A ab = new B()//object of B is created and reference variable is type of Super type as A is super class of B
since ab.m1() is type of A class and can be accessible through super variable.
ab.m2() is type of B class and can not be accessed using super type reference, thats where down casting comes into picture.
try:
B a = (B)ab;// down casting
a.m1();
a.m2();
now you call both method of B class.

How can i get the value of a variable through the Super keyword?

I have three class A,B,C class B extends A and class C extends B.
I want to get the value of the integer a present in the class A and print that value in class C. My first choice is to print through super keyword.
package testee;
import java.util.Scanner;
public class Testee {
public static void main(String[] args) {
new C();
}
}
class A{
int a=10;
A(){
System.out.println(a);
}
}
class B extends A{
int a=13;
B(){
System.out.println(a);
}
}
class C extends B{
int a=21;
C(){
System.out.println(super.a);
}
}
System.out.println(((A)this).a);
Having fields with the same name multiple times in a inheritance hierarchie is called "hidden fields".
Access to fields (and static methods) is based on the (static) type of the reference used. So that means if you cast the reference(here this) the type you want (in that case A) and access the field you get the field that belongs to A.
Would work the same way if you assign C to a variable. If the variable is of type A, you will get A.a.
Anyway: please, do not use hidden fields in production code

Is a class that creates an instance of another its parent?

If class A creates an instance of class B, then in class B can I run a method from class A? sorry if the question is poorly worded, I don't know how else I could say it.
In the below code, Class A creates an instance of Class B and you can call Class A's method from Class B's method.
class A {
public void getA() {
System.out.println("In A");
}
public static void main(String[] args) {
B b = new B();
b.getB();
}
}
class B {
public void getB() {
System.out.println("In B");
A a = new A();
a.getA();
}
}
Output:
In B
In A
In class B you can call methods of class A only if A's methods are visible to B. It doesn't matter who created an instance of B.
This tutorial might help: http://www.tutorialspoint.com/java/java_access_modifiers.htm
So you can call it if the method is one of the following:
public
protected (and B is a subclass of A or B is in the same package as A)
no modifier (and B is in the same package as A)

how does the call to overriden methods take place in case of dynamic dispatch

class a extends b {
void h() {
System.out.println("class a");
}
public static void main(String[]args) {
b x = new a();
c y = new b();
c z = new a();
x.h(); //output class a
y.h(); //output class b
z.h(); //output class a
}
}
class b extends c {
void h() {
System.out.println("class b");
}
}
class c {
void h() {
System.out.println("class c");
}
}
Whats is the precedence in which it checks which method to call. I am confused as to how the JVM decides which method to call when I use dynamic dispatch. The output in this case is
class a
class b
class a
and when I remove the overridden method from class a the output is
class b
class b
class b
The class used depends on the instantiated type. So if you have an instance of class a (via new a()), then whether the declared variable is of type a, b, or c does not matter for the purpose of which definition of h() is invoked (it will always invoke a.h()).
However, where the declared type does matter is in when choosing an overloaded method. If you have a subclass that overloads an overridden method, then when invoking from a variable declared as the parent class, you will never use the overloaded method. If using a variable declared as being of the subclass, then it will use the overloaded method as appropriate.

Categories