Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  
FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement


XyzWs Java FAQ: Run time binding or compile time binding?

Run time binding or compile time binding?


When we talk about the inheritance of class members, it's very important to remember when the binding occurs and what type they are bound to.

Only overridden instance methods are bound at run time; and this kind of binding depends on the instance object type. For example:

public class Parent {
  public void writeName() {
    System.out.println("Parent");
  }
}

public class Child {
  public void writeName() {
    System.out.println("Child");
  }

  public static void main(String [] args) {
    Parent p = new Child();
	p.writeName();
 }
}

The output is :

Child

Instance variables, static variables, static overridden methods (it looks like it's an override, but actually hidden), and overloaded methods are all bound at compile time; and this kind of binding depends on the type of the reference variable and not on the object. For Example:

public class Parent {
  private static String age = "50";
  private String hairColor = "grey";
  public void writeName() {
    System.out.println("Parent");
  }
}

public class Child {
 private static String age = "20";
  private String hairColor = "brown";
  public void writeName() {
    System.out.println("Child");
  }
  public void writeName(String order) {
    System.out.println(order + " Child");
  }

  public static void main(String [] args) {
    Parent p = new Child();
    System.out.println("age: " + p.age);
    System.out.println("hairColor: " + p.hairColor);
    Child c = new Child();
    c.writeName("first");
 }
}

The output is:

age: 50
hairColor: grey
first Child

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help