I have the following code:
import java.lang.*;
public class Program
{
public static void main(String [] args)
{
B a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i)
{
System.out.println(i*2);
}
}
class A extends B{
public void p(int i)
{
System.out.println(i);
}
}
When I execute this code using B a = new A() , I get 20.0 in both cases which makes sense because overloading is handles during compile time where the compiler looks at the declared type and calls a function appropriately. Since our declared type was class B, class B's method was called in both cases. Now if I do A a = new A(); , I should be getting 10 in both answers but I am not. I am getting 10 for a.p(10) and 20.0 for a.p(10.0). Based on the concept of static binding and whole notion of overloading being done by static binding which looks at the declared type as opposed to the actual type, why is the result coming out this way ? I would very much appreciate your help.
An int can be widened to a double, but not the other way around. This means that 10 can call B.p(double) or A.p(int) but 10.0 is a double and will not be implicitly converted to an int i.e. only B.p(double) will be called.
Its because your method p is not an overridden method, it is just inhereted in your sub-class when you use
Super sup = new Sub();
sup.p(int);
sup.p(double);
In this case as your Super class has a method which takes double as a parameter and aa an int can fit into a double your Super-class's method is invoked the one which accepts double.
Sub sup = new Sub();
sup.p(int);
sup.p(double);
In this case however, as your subclass doesn't have a method which takes a double, for sup.p(double) call it uses the inherited method from super class if you pass double as an argument.
In your case, your are doing overloading which will get binded at compile time(static binding.).And static binding happens with type of reference rather than the type of object the reference is pointing.
In your first case you are using a reference variable of B and assigning an object of A to it.Since your reference is B, the method p(double) from B will get binded statically even if you use an int(since int can be widened to double).
In the second case you are using reference as A itself.In this case, you have two p() methods available.One is p(double) from B and other p(int) from A.So p(10) will call p(int) and p(10.0) will call p(double)
Try this:
class B {
public void p(String i)
{
System.out.println("parent:"+i);
}
}
class A extends B{
public void p(int i)
{
System.out.println(i);
}
}
public class Test1 {
public static void main(String args[]) {
A a = new A(); //arg
a.p(10);
a.p("sample");
}
}
If you change the line marked arg to B a = new A(), you will see compiler trying to call parent p in both the cases.
When you write A a = new A() you create a new object of type A, which will have 2 methods. A.p(int) and B.p(double), and when you call A.p(10.0), it will call B.p(double) due to lack of conversion.
This counter-example might help:
import java.lang.*;
public class X
{
public static void main(String [] args)
{
B c = new A();
c.p(10);
c.p(10.0);
c.p("AAA");
((A)c).p(10);
}
}
class B {
public void p(String s)
{
System.out.println("B: my string is " + s);
}
public void p(double i)
{
System.out.println("B: twice my double is: " + i*2);
}
}
class A extends B{
public void p(int i)
{
System.out.println("A: my number is " + i);
}
}
Output:
C:\temp>java X
B: twice my double is: 20.0
B: twice my double is: 20.0
B: my string is AAA
A: my number is 10
The issue is:
1) You're declaring the type as "B" (not "A")
2) B.p(10) can accept an int as a floating point argument
3) Consequently, that's what you're getting
It's really an issue of what argument types can be implicitly converted, than what methods are overloaded or overridden.
When the object has declared type B, the double version is invoked because it's compatible with an int argument, since in Java int is a subtype of double.
When the object is declared as a A, it has the method p() overloaded with two versions:
p(int arg);
p(double arg);
So, when you pass an int, the first version is picked because it's more accurate, and when you pass double the second one, because it's the most specific signature.
For reference, see the relevant JLS at §15.12.2 and this post by Gilad Bracha. BTW, don't try to figure out how the language should behave based on what you think is the most logical way, because every programming language is an engineering effort, and this means that there's a price you pay for whatever you take. The primary source of information for Java are the JLS, and if you read it carefully, you'll (surprisingly?) discover that there are even cases where the line in the source code is ambiguous and cannot be compiled.
To make the effect of widening of int to double more vivid I have created another example which is worth looking. Here, instead of double I have created a class called Parent and instead of int a Child class is created.
Thus,
double ~ Parent int~Child
Obviously child object can be widened to Parent reference.
package test;
public class OOPs {
public static void main(String[] args) {
Child ch = new Child(); // like int 10
Parent pa = new Parent();// like double 10.0
B a = new A(); // case 2 : A a = new A();
a.p(ch);// 10
a.p(pa);// 10.0
}
}
class B {
public void p(Parent i) {
System.out.println("print like 20");
System.out.println(i.getClass().getName());
}
}
class A extends B {
public void p(Child i) {
System.out.println("print like 10");
System.out.println(i.getClass().getName());
}
}
class Parent {
String name;
Parent() {
name = "Parent";
}
public String getName() {
return name;
}
}
class Child extends Parent {
String name;
Child() {
name = "Child";
}
public String getName() {
return name;
}
}
Case 1 - Output (B a = new A();)
print like 20
test.Child
print like 20
test.Parent
Case 2 - Output (A a = new A();)
print like 10
test.Child
print like 20
test.Parent
Related
class A{
int a = 10;
}
class B extends A{
int a= 20;
}
public class C {
public static void main(String [] args){
A a = new B();
System.out.println(a.a);
}
}
output : 10
How it print value from base class based on above code.
B already inherits a from A. Doing int a = 20; again hides the a inherited from A. This means that an expression of the form x.a will only evaluate to 20 if the compile time of x is B.
To get your expected behaviour, you can reset a in the constructor of B:
class B {
// no need to redeclare "a" here!
public B() { a = 20; }
}
When you make a variable of the same name in a subclass like you have done here, its called hiding. The resulting subclass will now actually have both properties.
Please refer below image,
1.Can Some one illustrate how it works? Why it prints 1 instead of 2?
2.From the Oracle Official Java tutorial, the definition of this: Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
// Base Class
class A {
public int m = 1;
public void view(){
// Print variable m
System.out.println(this.m);
//print the current class name
System.out.println(this.getClass());
}
}
// Subclass extends Base Class
public class B extends A{
// Define another variable m
public int m = 2;
public static void main(String[] args) {
B b = new B();
b.view();
}
}
Below is the debug of the view(){}:
My Question is:
You can see the current object is B, when we usethis, it represents the B, m = 1 in base class A, m = 2 in derived class B, then use the this.m, it should print 2, isn't it?
Variables are not polymorphic in Java; they do not override one another.
consider the following code:
public class A{
private int num;
public A(int n){
num = n;
}
public int getNum(){
return num;
}
public boolean f(A a){
return num == a.num * 2;
}
}
public class B extends A {
public B(int n) {
super(n);
}
public boolean f(B b) {
return getNum() == b.getNum();
}
}
public class Main
{
public static void main(String[] args){
A y1 = new B(10);
B y2 = new B(10);
System.out.println("y1.f(y2) is: "+y1.f(y2));
}
}
What I don't understand is why the method f is running for class A (and printing false) and not B, cause in run time y1 is of type B, and should go down to method f in class B?
cause in run time y1 is of type B, and should go down to method f in class B?
No:
B.f() doesn't override A.f() because the parameter types are different. It overloads it.
Overloads are picked at compile-time, not at execution time
If you change B.f() to accept a parameter of type A rather than B, you'll see it get executed. That doesn't depend on the execution-time type of the argument, but on the execution-time type of the target of the call.
The method implementation which is chosen never depends on the execution-time type of an argument.
pay attention that the parameters in class B & class A in f function are diffrent. that is the reason that the "gravity low" dont exist here and this time it enter to the A.f function
my question may not been very clear. looking through this example, I can explain further.
As I reading the answers posted for this Static vs Dynamic Binding Logic , I got this question.
There are two version of code, both of which are exactly the same, except for change in parameter type for Class B p (double i)
version 1:
import java.lang.*;
public class X
{
public static void main(String [] args)
{
B c = new A();
c.p(10);
c.p("AAA");
((A)c).p(10);
}
}
class B {
public void p(String s)
{
System.out.println("B: my string is " + s);
}
public void p(int i)
{
System.out.println("B: twice my double is: " + i*2);
}
}
class A extends B{
public void p(int i)
{
System.out.println("A: my number is " + i);
}
}
Here the output is :
A:my number is 10
B: my string is AAA
A: my number is 10
version 2:
import java.lang.*;
public class X
{
public static void main(String [] args)
{
B c = new A();
c.p(10);
c.p("AAA");
((A)c).p(10);
}
}
class B {
public void p(String s)
{
System.out.println("B: my string is " + s);
}
public void p(double i)
{
System.out.println("B: twice my double is: " + i*2);
}
}
class A extends B{
public void p(int i)
{
System.out.println("A: my number is " + i);
}
}
Here the output is :
B:twice my double is 20.0
B: my string is AAA
A: my number is 10
my question is as follows:
why the p(int) from Class A is called in the first version while p(double) from Class B is called in the second version.
version 1:
methods of A
A -----> p(string), p(int)- this is overridden from Class B
method of B
B ------> p(string), p(int)
version 2:
methods of A
A -----> p(string), p(double), p(int) No more overriding
method of B
B ------> p(string), p(double)
when I declare B c;, I initialize the reference variable which is of type B
next I assign c to the new object, by c = new A();
hence this declaration B c = new A(); creates an instance of class A and assigns to the variable of type B. now whenever the methods calls are executed on c, the compiler first checks if the methods exists in B (since it is of B type), but the actual method that is called is of the object (which is an A instance).
why this behavior is not seen in the above example? or if my reasoning is wrong, kindly correct me.
Thanks
In the first version you override a method and in the second method you overload it.
In the first version you have p in both class A and class B. When you call c.p(...) the compiler uses the static type of c to create the call. On run time the code uses the class`s virtual table (read about it if you're not familiar) in order to find the correct polymorphic method.
In the second version the compiler does the cast from int to double for you on compile time and then on run-time it again uses the virtual table of A to find a method with signature p(double) (because it casted the int on compile-time for static-type compliance). The virtual table points to the method in B because A doesn't override it.
You can further read about it in the book "Effective Java" - Item 41, Page 191:
selection among overloaded methods is static, while selection among overridden methods is dynamic
How to initialize the values in constructor that the values cannot be passed by object and that we could pass them from main method?
class ex
{
int a,b;
ex()
{
this.a=b;
}
public static void main(String args[])
{
//here we pass the values to that consructor ex
ex obj=new ex();
}
}
make an overloaded constructor which accepts two arguments.
public ex(int a, int b) {
this.a = a;
this.b = b;
}
public static void main(String...args){
ex obj = new ex(1,2)
}
values canntot be passed by object we should pass from main method
If i understand correctly, you want to pass arguments from the main method and nitialize them in your constructor, the only was to do is by passing them to the constuctor while object creation
You can call setter method from constructor if don't want to display initialization values while declaring new object.
Please see code below for reference :
class Testcl {
int a,b;
Testcl(){
setValues(1,2);
}
private void setValues(int a, int b){
this.a=a;
this.b=b;
}
public static void main(String [] args){
Testcl test = new Testcl();
System.out.println("a : " + test.a + " b : " + test.b);
}}
The first thing to say is that this does actually "work" ... in the sense that it compiles and executes without any errors.
int a,b; // default initialized to 'zero'
ex() {
this.a=b; // assigns 'zsro' to a.
}
But of course, it doesn't achieve anything ... because a is already zero at that point.
Now the main method could assign something to the a and/or b fields after the constructor returns. But there is no way (in pure Java1) to get some non-zero value into b before the constructor is called ... if that is what you are asking.
The practical solution is to just to add a and b arguments to the constructor.
1 - a non-pure Java solution might be to "monkey around" with the bytecodes of the constructor so that it does what you "need" to do. But that's pretty horrible, and horrible solutions have a tendency of coming back to bite you.