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
Related
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
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
I am having confusion in java polymorphism. In dynamic method binding jvm decides at run time which class method has to call. Suppose I am having three classes A, B and C.
class A{
int get(){
return 10;
}
int getParent(){
return 10;
}
}
class B extends A
{
int get(){
return 20;
}
}
public class C
{
public static void main(String args[])
{
A a = new A();
A a1 = new B();
System.out.println(a.get());/////////////////////////LINE1
System.out.println(a1.get ());////////////////////////LINE2
System.out.println(a.getParent());////////////////////////LINE3
}
}
I am having confusion in line 1 and line3 at compile time and runtime binding.
In line 3 it a.getParent() and this method is in parent class only so what it has to decide at runtime.
In line 1 both reference and object are from same class so again what it has to decide .
Please send me any good link for runtime and compile time binding how works.
class A
{
public doIt( )
{
//this does something
}
}
class B extends A
{
public doIt( )
{
//this does something
}
}
class C extends B
{
public doIt( )
{
//this does something
}
}
public static void main(String[] args) {
A x = new B( );
x.doIt( );
}
The statement that causes a lot of confusion is the “A x = new B();” statement. Although the variable x is an object of type A, it is instantiated as an object of class B – because of the “= new B( );” part of the statement. The Java runtime will basically look at this statement and say “even though x is clearly declared as type A, it is instantiated as an object of class B, so I will run the version of the doIt() method that is defined in class B.”
The version of the doIt() method that’s executed by the object x is the one in class B because of what is known as dynamic binding in Java – the code above can be considered to be an example of dynamic binding. Dynamic binding basically means that the method implementation that is actually called is determined at run-time, and not at compile-time. And that’s why it’s called dynamic binding – because the method that will be run is chosen at run time. Dynamic binding is also known as late binding.
In early binding the data and method are binds at the complie time where as in
late binding the data and method will bind at the runtime.
Class B overrides the get() method. So whenever you call get() on an object that is of type B it will use the overridden method.
Because B doesnt override getparent(), then the parent getParent() will be called when you call it on class B
Class A provides the Object instance a with a virtual method table, containing A.get and A.getParent.
Class B provides the Object instance a1 with a virtual method table, being first taken from class A, and expanded (here nothing to expand with). The get method is overwritten with B.get.
a1.get, even being a A, will call B.get.
polymorphism here applies only in the case of line2. There is no concept of polymorphism applied to line1 and line3.
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.
public class A
{ }
public class B extends A
{
public void add()
{
System.out.println("add in B");
}
}
Now here if we call add in following way hen it gives an error:
A a1 = new B;
a1.add();
But when we add the add() method in class A and then call in the similar fashion then add() method of child class is called.
i.e.
public class A
{
public void add()
{
System.out.println("add in A");
}
}
public class B extends A
{
public void add()
{
System.out.println("add in B");
}
}
call:
A a1 = new B;
a1.add();
output:
add in B
Why is it so?
at the method invocation of a1.add() the compiler checks if the method is present. But it only knows that a1 is a reference to an object of class A, which does not have that method. So the compilation fails.
In this trivial example it would probably be easy for the compiler to deduct the correct type. But in more general cases it wouldn't. And therefore this kind of logic is not part of the specs.
Because java does not know at compile time that a1 will refer to an instance of B at runtime. It only knows the declared type, so it only allows calls that work with the declared type.
When the Java compiler looks at the reference a1, it knows what methods are available. In your first example, class A does not have add() in its API. It is legal in this case to perform a cast of a1 to B like so:
((B)a1).add();
and the compiler will not complain.
You want to call a method on an object of declared type A but implement it only in a subclass B of A.
In this situation you would normally make A an abstract class and declare add() an abstract method in A.
Good answers...I had a doubt too regarding this but now I am clear :)
And one more thing ..you don't have to go into the trouble of declaring an abstract method,just make an empty method with the same name and signature in your parent class and " voila " all compilation errors are gone ;)
In your case you can add a void add(){} method like this and you wont have any problems