Inheritance and the "this" keyword - java

Suppose that we have next situation:
Parent class A:
class A{
public A(){}
public doSomething(){
System.out.println(this.getClass());
}
}
with a child class B:
class B extends A{
public B(){}
public void doSomething(){
super.doSomething();
System.out.println(this.getClass());
}
}
and Main class:
class Main{
public static void main(String[] args){
A ab=new B();
ab.doSomething();
}
}
When I execute this code result is
B
B
Why does this, referenced in superclass A, returns B as a class when the reference is of type A?

It doesn't matter what the reference is, it's the instantiated object's class that counts. The object that you're creating is of type B, therefore this.getClass() is always going to return B.

Despite the fact that you are calling the doSomething() method of A, the this during that call is a B, and so the getClass() method is called on B not on A. Basically the this will always be a B whether you are using a method from superclass A, a method from B, or from A's superclass Object (the parent class of all Java classes).

this doesn't do anything for you in this situtaion. Calling this.getClass() is no different than just calling getClass();
So, A calls getClass(), which will return B if you are dealing with an instance of B that extends A.

Think of it in terms of runtime vs static types:
Animal a = new Cat();
The static type (in this case written on the left hand side) of variable a is Animal (you couldn't pass a into a method that required a Cat without a downcast) but the runtime type of the object pointed to by a is Cat.
a.getClass() exposes the runtime type (if it helps think of it as the most specific subtype).
Interestingly in Java overloaded methods are resolved at compile-time (without looking at the runtime type). So given then following two methods:
foo(Cat c);
foo(Animal animal)
Calling foo(a) would call the latter. To 'fix' this the visitor pattern can be used to dispatch based on the runtime type (double dispatch).

The output of program is correct.
When in Main class ab.doSomething(); line get executed doSomething() method of class B will be called then super.doSomething(); line will call doSomething() method of class A. As this keyword indicates reference of current object(ab is the object of class B see A ab=new B(); as constructor is of class B),i.e.System.out.println(this.getClass()); line in class A will print B only.
Again control will come back to System.out.println(this.getClass());in class B, So again B will get print.
In birdeye view only object of class B has created. That is why we are getting B B in output.

Related

Runtime Polymorphism giving wrong output

To my understanding, the following code should print a as per my knowledge of run time polymorphism.
However, when I run the following code it is printing b:
Per JLS 8.4.8.1, B1.m1 does not override A1.m1, and so when A1.m1 is
invoked, B1.m1 should not be selected
package a;
public interface I1 {
public Object m1();
}
public class A1 {
Object m1() {
return "a";
}
}
public class C1 extends b.B1 implements I1 {
public static void main(String[] args) {
a.A1 a = new a.C1();
System.out.println(a.m1());
}
}
package b;
public class B1 extends a.A1 {
public String m1() {
return "b";
}
}
Can some one help me understand this behavior.
After adding the packages, the question is much more difficult. I've tried this, and I changed your main program to
public class C1 extends b.B1 implements I1 {
public static void main(String[] args) {
a.A1 a = new a.C1();
System.out.println(a.m1());
a.A1 b = new b.B1();
System.out.println(b.m1());
}
}
(I actually used different package names to avoid conflicts with the variable names. So my code looks a bit different from the above.)
I've confirmed that this prints "b" and "a". That is, if I create a new B1, its m1 method does not override the one in A1. Thus if I print b.m1(), since b is of type A1, polymorphism doesn't kick in, and the method declared in A1 is called. So what's going on with C1?
C1 inherits the m1 method from B1. But even though the m1 method in B1 doesn't override the one in A1, the m1 method in C1, which it inherits from B1, actually does override the one in A1. I think it has to do with this clause in 8.4.8.1:
mA is declared with package access in the same package as C, and either C declares mC or mA is a member of the direct superclass of C.
Here C is your C1 class. mC is the m1 that's inherited from B1. In this case, "C declares mC" is false, because C1 doesn't declare m1, it inherits it. However, I believe "mA is a member of the direct superclass of C" is true. As I understand it, B1 has all the members that A1 has. B1 declares its own m1, and since it's not overriding, it's a new m1 that causes the m1 it inherits from A1 to be hidden. But even though it's hidden, it's still a member. Thus the condition that mA is a member of the direct superclass of C (which is B1) is satisfied, and thus all the conditions of 8.4.8.1 are satisfied and thus the inherited m1 in C1 overrides the one in A1.
The expected output is indeed b.
When you declare your object a as being of the type A1, that class defines only the interface of the methods. It defines that m1 returns a String, but the implementation of that method is defined by the Class used to build the object, which is Test1. And Test1 extends B1, which overrides the method m1, so that is the implementation of m1 used for your object.
The output of that call m1() must be indeed the B1's.
EDIT: This answer was written for the first version of the question. OP changed a lot of the code, but the root of the explanation is still the same.
The following line A1 a = new Test1(); simply means build a Test1 instance and store it in a A1 box.
So the instance will be a Test1, but you will only have access to the method/variable of A1, but every overriden method in Test1 will be accessed.
This is polymorpish.
By reading the JLS about 8.4.8.1. Overriding (by Instance Methods) about the accesor
An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:
A is a superclass of C.
The signature of mC is a subsignature (§8.4.2) of the signature of mA.
mA is public.
You can find more information about the access modifiers in 8.4.8.3. Requirements in Overriding and Hiding
The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
If the overridden or hidden method has package access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.
EDIT :
Now, with your package added.
Having C1 to implement m1 (because of the interface), you are hiding the method of A1 with the implementation you find in B1, this method is indeed a valid definition for the interface contract.
You can see you are not overriding the method (you can't call super.m1 or even add #Override on the B1.m1. But the call a.m1() is valid as it is define in the class itself.
You are Overriding. Include the #Override annotation and you can see that. As long as your class extending can override the parent class method, you can increase the access, but not decrease the access.
If you tried to make B#m1 private, then somebody could just cast to an A and use the method.
Conversely, if you make A#m1 private, then B cannot override it and you can end up with an object having two methods with the same signature.
static class A{
private String get(){
return "a";
}
}
static class B extends A{
public String get(){
return "b";
}
}
public static void main (String[] args) throws java.lang.Exception
{
A b = new B();
System.out.println(b.get());
System.out.println(((B)b).get());
// your code goes here
}
This will output:
a
b
All comments and answers are mostly correct. They explain things in term of language mechanisms. I think, instead, that to realise the real meaning of inheritance and polymorphism and how to use them, you have to take a more conceptual approach.
First of all inheritance is a relationship between two things and the relationship is of the type “is a”. In other words when you write the statement class C1 extends B1 you mean C1 is a B1.
Of course this won’t work with A1, B1 and C1. Let me change them in something more real. For example:
A1 = Animal
B1 = Feline
C1 = Cat and C2 = Lion (polymorphism)
At this point you will have class Cat extends Feline, and you can conceptually read it as: Cat is a Feline. I suggest to challenge your inheritance formal correctness using the “is a” test. If it doesn't work, it is better to reconsider or rethink the inheritance.
Your resulting code will be like the following:
public interface IAnimal {
public Object saySome();
}
public class Animal {
Object saySome() {
return "I am an animal";
}
}
public class Feline extends Animal {
public String saySome() {
return "I am a feline";
}
public class Cat extends Feline implements IAnimal {
Object saySome() {
return "meow";
}
}
public class Lion extends Feline implements IAnimal {
Object saySome() {
return "roar";
}
}
class Aplication {
public static void main(String[] args) {
Animal anAnimal = new Cat();
Animal anotherAnimal = new Lion();
System.out.println(anAnimal.saySome());
System.out.println(anotherAnimal.saySome());
}
}
And clearly the output will be
meow
roar
I hope this will help.
You have an interface I1, which is implemented by A1
Class B1 extends A1
Class C1 extends B1 (and therefore implicitly extends A1).
So an instance of C1 is also of type B1, A1 & I1, however it remains an instance of C1 regardless of whether you assign it to one of the other types.
If you have:
I1 instance = new C1();
String value = instance.m1();
The first m1 method going up the inheritance tree from the real type (C1) will be called, which will be in B1 and return "b".

Is Method overloading allowed across the classes? Please explain why and how?

My Code:
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
B b = new B();
b.p();
}
}
class A{
void p(){
System.out.println("A");
}
}
class B extends A{
void p(int a){
System.out.println("B :"+a);
}
}
Is method overloading allowed across the classes? Because this is working in Java. According to concepts I highly doubt this as in C++ and C# gives error but java compiler invokes correct version of function which is not expected.
Please explain why and how ?
Yes overloading works here because class B inherits the overloaded method from class A. This is specified in the Java Language Specification:
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.
In this program, When p() is called by using the object of B class, it will invoke the p() of A class as p() present in B class is having p() with integer parameter, which is not matching with the calling p().
Then it will search p() with no parameter inside the A class and it will find the p() with same signeture, so it will execute p() of A class.
if you are calling the method from an instance of Class B object, the method in class B would be called, if you are calling it from a method from an object of class A, even if its a class B wrapped in class A, the class A's method would be called instead

Polymorphism inside constructors in Java

Code:
class A{
A() {
test();
}
void test(){
System.out.println("from A");
}
}
class B extends A {
void test() {
System.out.println("from B");
}
}
class C {
public static void main(String args []){
A a = new B();
a.test();
}
}
Output:
from B
from B
Why is it getting printed that way ?
This is extremely bad code. What's happening is that void test() is being overridden in the child class B.
new B(); creates an instance of class B. The fact that you reference cast it to A is not relevant here. But even though the child class has not yet been constructed, the Java runtime calls a method in that child class from the constructor of the parent class A.
Use this (anti)pattern with extreme caution! (Note that in C++ you get undefined behaviour).
When you call a polymorphic method at runtime, Java uses a special data structure to decide a method of which class needs to be called. This structure is set up at the time the object is constructed, before any of the user-supplied constructor and initializer code get executed.
When you create A a = new B(), the data structure that says "when test() is called, you need to call A.test() or B.test()" is prepared before the constructor of A is entered. Since this structure is prepared for the B class, it points to B.test(), even though the calling code is inside A's constructor. That is why you see "from B" printed twice.
Note, however, that although technically your code will do what you want, logically it is a very poor decision. The reason why this code is bad has to do with the initialization sequence: imagine a test() method that relies on private fields of B being initialized in the constructor, like this:
class B extends A {
private final String greeting;
public B() {
greeting = "Hello";
}
void test() {
System.out.println(greeting + " from B");
}
}
One would expect to see "Hello from B" being printed. However, you would see it only in the second call: at the time the first call is made, greeting is still null.
That is why you should avoid calling method overrides from inside a constructor: it breaks method's assumption that the object has been fully initialized, sometimes with rather unfortunate consequences.
During runtime, the method is invoked from actual instance object. i.e B.
A a = new B();
a.test();
In the above code, You have instantiated Object B, not A. You have just assigned the reference variable of type A. Internally, it is referring only an instance of B. During compilation, it just checks whether the method is actually present in A reference and allow it to compile. During Runtime, the method is actually invoked on the real object i.e. B referred by the reference A
This is one of the most important concepts of Object Oriented polymorphism.
By extending A with class B you are creating a more specific implementation of it, overriding some of its methods with new ones (such as your test() method) and potentially adding things to it (members and methods).
Whenever you override a class, the methods of the subclass will be invoked, irrespective of which class they are 'acting' to be.
When you cast an object to another class (like in your case B to A) you are just saying I want to see it as a reference of type A. This is useful for methods that accept objects of type A as parameter.
Consider this example:
Employee (super class) which has method float computeSalary()
Technician extends Employee which overrides method float computeSalary()
Manager extends Employee which overrides method float computeSalary()
The SalaryGenerator class has a method generateMonthlyPay(Employee e) that calls the computeSalary() of the Employee superclass, but the specific sub-class method will be invoked, because each have a different way of calculating their monthly salary.
Although the reference type is A, it's object type is B which means that it is pointing to the implementation in B. Hence, from B gets printed.
When the object a is created using,
A a = new B()
the constructor gets invoked from base class to derived class.. here the base class constructor calls test(), but this calls test() in derived class because of the over riding concept.
So you get " from B" initially.
Again a.test() calls the over rided derived class test(). So again from B is printed

Multiple casting on inherited objects

interface I{
}
class A implements I{
}
class B extends A {
}
class C extends B{
public static void main(String args[])
{
A a = new A();
B b = new B();
b = (B)(I)a; //Line 1
}
}
I know this is not an actual code :)
I just need to know how the casting gets done at Line 1.
I know the reference variable 'a' gets cast to Class B/Interface I.
But I am not sure of the sequence in which the casting takes place..can someone tell me which cast gets executed first.
PS : I searched for similar posts but most of them were from C++.If a similar post is already there wrt to Java do point it..tx
a gets cast to type I first, and then to type B, as casting is right-associative.
Why would you cast it in the first place? This is multiple level inheritance but what happens here is all them methods in class I get inherited by class A, as class B inherits class A the methods in class A get passed onto class B. This means that all the methods class A inherits will also be in class B
That means class B is also a type of class I and therefore i believe there is no need to cast at all

Regarding overriding principle

I have a question and below is my code.
class A
{
int i=10;
public void m1() {
System.out.println("I am in class A");
}
}
class B extends A
{
public void m1() {
System.out.println("I am in class B");
}
}
class main2 extends A
{
public static void main(String...a) {
A a1= new B();
a1.m1();
}
}
Now my question; it's OK to get the variable "i" of the parent class A, but the method that I am getting is also of class A. Is it getting class B's method, as it overrides class A's method?
In Java, any derived class object can be assigned to a base class variable. For instance, if you have a class named A from which you derived the class B, you can do this:
A a1 = new B();
The variable on the left is type A, but the object on the right is type B. As long as the variable on the left is a base class of B, you are allowed to do that. Being able to do assignments like that sets up what is called “polymorphic behavior”: if the B class has a method that is the same as a method in the A class, then the version of the method in the B class will be called. For instance, if both classes define a method called m1(), and you do this:
a1.m1();
the version of m1() in the B class will be called. Even though you are using an A variable type to call the method m1(), the version of m1() in the A class won’t be executed. Instead, it is the version of m1() in the B class that will be executed. The type of the object that is assigned to the A variable determines the method that is called.
So, when the compiler scans the program and sees a statement like this:
a1.m1();
it knows that a1 is of type A, but the compiler also knows that a1 can be a reference to any class derived from A. Therefore, the compiler doesn’t know what version of m1() that statement is calling. It’s not until the assignment:
A a1 = new B();
is executed that the version of m1() is determined. Since the assignment doesn’t occur until runtime, it’s not until runtime that the correct version of m1() is known. That is known as “dynamic binding” or “late binding”: it’s not until your program performs some operation at runtime that the correct version of a method can be determined. In Java, most uses of inheritance involve dynamic binding.
Yes, it calls the B implementation of m1. When you run this code, it prints
I am in class B
just as expected. (Note that you don't actually use i in any of the code you posted, so I'm not sure what the first part was about...)
Yes it will invoke B's version of method, Since the object is of class B

Categories