Employee.java
public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
}
VirtualMethod.java
class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int number, double
salary)
{
super(name, address, number);
this.salary=salary;
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to "
+ " with salary " + salary);
}
}
public class VirtualMethod
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
Wyjście
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to with salary 2400.0
Wyjaśnienie
tutaj, my wystąpienia dwóch Salary
obiektów. Jeden używający Salary
odniesienie s
, a drugi używający odniesienie e
.
Podczas wywoływania s.mailCheck()
kompilator widzi mailCheck()
w klasie Salary
w czasie kompilacji, a JVM wywołuje mailCheck()
w klasie Salary
w czasie wykonywania.
Wywołanie mailCheck()
na e
jest zupełnie inne, ponieważ e
jest numerem referencyjnym Employee
. Gdy kompilator zobaczy e.mailCheck()
, kompilator zobaczy metodę mailCheck()
w klasie Employee
.
Tutaj, podczas kompilacji, kompilator użył mailCheck()
w Employee
do sprawdzenia poprawności tej instrukcji. Jednak w czasie wykonywania JVM wywołuje mailCheck()
w klasie Salary
.
[Metoda wirtualna] (http://en.wikipedia.org/wiki/Virtual_method) –
również http://pl.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming – stryba
Dziękujemy za referencje. – Popokoko