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 extends Parent {
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
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?