Question about dynamic typing in Java

I got this from berkley cs data webcast:

class A {
  void f() {System.out.println("A.f");}
  void g() {f();}
 // static void g(A y) {y.f();}
}

class B extends A {
  void f(){
    System.out.println("B.f");
  }
}

class C {
  static void main (String[] args){
    B aB = new B();
    h (aB);
  }

  static void h (A x) {x.g();}
  //static void h (A x) {A.g(x);}  what if this were h 

}

Can you tell me what prints and why? The instructor told Bf, but I do not understand why. I thought it was Af Thank you (no, I'm not in class, just trying to learn.)

Edit: Sorry for the errors that I copied from the video lecture.

+3
source share
3 answers

The reason for "Bf" is that the method implementation is determined by the type of runtime of the object, and not by its type of compilation time. This is similar to a keyword virtualin C ++.

B, , f "B.f", B A.

, A.f .

+1

- .

ab B, ab , B, , , .

, . :

class Employee
{
  ... bunch of stuff ...
  void calcPay()
  {
    pay=hoursWorked*hourlyRate;
  }
  void produceCheck))
  {
    calcPay();
    calcTaxes();
    calcBenefitDeductions();
    printCheck();
  }
}
class Salesman extends Employee
{
  void calcPay()
  {
    pay=sales*commissionRate;
  }
}
... somewhere else ...
for (Employee employee1 : employeeList)
{
  employee1.produceCheck();
}

, : .

: , : , . ( , , , .) , . - , , , , . , , . , , , , . : "if (type == SALESMAN)... else if (type == HOURLY)..."

+2

, A.g() .

static void h (A x) {A.g(x);}

Ag (x); tries to call a static method for A called g with x as an argument. This is not possible with the code example you provided.

except for the wrong code, the reason in B overrides the f () method with its own implementation. Thus, any cases of B, such as B x = new B (); will call f () that B defines not Af (). The only way to get to Af () would be from within instance B by calling super.f ();

+1
source

Source: https://habr.com/ru/post/1730258/


All Articles