Polymorphism java thinking - java

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

Related

Passing arguments to Method References

Given this method:
private static Integer getVal(Integer a, Integer b){
return a + b;
}
which can be called as a lambda:
a -> getVal(1, 2)
Is there anyway of turning this into a method reference, something like:
Class::getVal
Thanks
Well, if you are passing constants to the method call, you can create another method that calls the original method:
private static Integer getVal (Integer a) {
return getVal(1,2);
}
then you can use method reference for the second method.
i.e. you can change
a -> getVal(1, 2)
to
ClassName::getVal
That said, it doesn't make much sense.
P.S., it's not clear what's the purpose of a in your lambda expression, since you are ignoring it.
In general you can pass a method reference of a given method if it matches the signature of the single method of the required functional interface.
Example:
public static Integer apply (BinaryOperator<Integer> op, Integer a, Integer b)
{
return op.apply(a,b);
}
Now you can call:
apply(ClassName::getVal)
with your original method.
Here is an example.
interface Operator {
int operate(int a, int b);
}
class Calc {
public static int add(int a, int b) {
return a + b;
}
}
class Main {
public static void main(String[] args) {
// using method reference
int result = operate(1, 2, Calc::add);
// using lambda
int result = operate(1, 2, (a, b) -> Calc.add(a, b));
}
static int operate(int a, int b, Operator operator) {
return operator.operate(a, b);
}
}
You need a functional interface to use method reference (In this example Operator). And you also need a method which accepts an instance of the functional interface as its parermater (In this example operate(int a, int b, Operator operator).
UPDATE
If you need an object wrapper, just change the operate method to
static int operate(ObjectWrapper wrapper, Operator operator) {
return operator.operate(wrapper.getA(), wrapper.getB());
}
And then call the operate method:
int result = operate(wrapper, Calc::add);
getVal() will only be usable as a method reference, in places where a functional interface of an applicable type is expected, such as BiFunction or IntBinaryOperator, or a custom functional interface (as in the answer of zhh)
Example:
public static void main(String[] args) {
Integer result1 = calculate(1, 2, Second::getVal);
Integer result2 = calculateAsInt(1, 2, Second::getVal);
}
private static Integer getVal(Integer a, Integer b){
return a + b;
}
private static Integer calculate(Integer a, Integer b, BinaryOperator<Integer> operator) {
return operator.apply(a, b);
}
private static int calculateAsInt(int a, Integer b, IntBinaryOperator operator) {
return operator.applyAsInt(a, b);
}

(Java) Pass a parameter from a constructor to all the methods of a class

Say I have two methods in class 1. Can I pass a parameter to class 1 constructor which would then pass the parameter to both of the methods? Something like the example code below:
class stuff{
int c;
stuff(x){
c = x;
}
public static int sum(int a, int b){
stuff self = new stuff();
return c*(a + b);
}
public static int mult(int a, int b){
return c*(a*b);
}
}
class test{
public static void main(String args[]){
stuff foo = new stuff(5);
System.out.println(stuff.sum(1, 2));
System.out.println(stuff.mult(1, 2));
}
}
So from class test I want to access both methods from class stuff, while passing the parameters for the methods, but I also want to pass a global class parameter (5 in this case). How can I do this?
First two important things :
Constructors are designed to create instances.
Class names should start with an uppercase.
As you write :
class Stuff{
int c;
Stuff(x){
c = x;
}
...
}
Here you assign x to a c field.
But sum() and mult() are static methods.
They cannot use the c field.
Make these methods instances methods and you could use c in these methods.
public static void main(String args[]){
Stuff foo = new Stuff(5);
System.out.println(foo.sum(1, 2));
System.out.println(foo.mult(1, 2));
}
And use the current instance in these instance methods to sum or multiply current value with passed parameter values :
public int sum(int a, int b){
return c*(a + b);
}
public int mult(int a, int b){
return c*(a*b);
}
Just remove 'static' keyword from your methods, and do not create new instance of 'stuff' in a sum method. Instead just create instance of stuff in test#main method like you do right now, and it will work like you wanted.

Overloading method on extended class

Simple question, strange result. I have two classes A and B:
public class A
{
protected int num;
public A(int n)
{
num = n;
}
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 num == b.num;
}
}
Why does y1.f(y2) call the f() method in A instead of in B?
A y1 = new B(10);
B y2 = new B(10);
System.out.println(y1.f(y2));
Is it not supposed to call f() in B as B is more specific than A?
Why does y1.f(y2) calls the f() method in A instead of in B?
Because the compile-time type of y1 is A.
Overloading is performed at compile-time... the execution-time type of the object you call the method on is only relevant for overriding.
So the compiler is choosing the method f(A) as that's the only f method it's aware it can call on y1 (and it's checked that it's applicable given the argument list). That method isn't overridden in B, therefore at execution time, the implmenetation in A is called.
As a starker example, consider this code:
Object x = "foo";
int length = x.length();
This won't even compile, because Object doesn't contain a length() method. String does, but the compiler doesn't consider that, because the compile-time type of x is Object, not String - even though we can tell that at execution time, the value of x will be a reference to a String object.

Java snippet output not understood, probably related to polymorphism

I was wondering why this bit of Java yields 2, and not 3 :
public class Test {
private static class A {
int f(A a) {
return 1;
}
}
private static class B extends A {
int f(A a) {
return 2;
}
int f(B b) {
return 3;
}
}
public static void main(String[] astrArgs) {
A ab = new B();
B b = new B();
System.out.println( ab.f(b) );
}
}
I came across this in a test question, and couldn't get the logic behind it.
The compile-time type of ab is just A. Therefore, when the compiler sees this expression:
ab.f(b)
... it only considers method signatures declared on A and its superclasses (just Object in this case).
So, the compiler makes the decision to call the method with the signature f(A a).
Now at execution time, the VM chooses which implementation of that signature to execute based on the execution-time type of the target of the method call, which is B.
B overrides f(A a), so that overriding implementation is called - and returns 2.
Basically, overloading is determined at compile-time to work out what method signature to call based on the compile-time types of both the target of the call and the arguments, and overriding is determined at execution-time to work out the exact implementation to execute based on the execution-time type of the target object.
In this case, ab is of type A, but instantiated as B. A only knows method
int f(A a) {
return 1;
}
b is of type A, so it is valid. B overrides int f(A a), so this method is used.
int f(A a) {
return 2;
}
Hope that helps.

Static vs Dynamic Binding Logic

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

Categories