Simple Inheritance Example in Spring
Friday, June 11, 2010
Inheritance is a very commonly used feature in Java to extended the functionality of an existing class. Let us see a very simple example how inheritance can be achieved in Spring.
Step 1. Create two Java classes with one class extending the other.
In this example we have Father and Child class. The Father class has two properties firstName and lastName. In the Child class we will only have one property firstName since we want to override the value.
Also, in the Father class we have a method which shows full name using the first and last name values. We will inherit the same method in the child class and use it to display the full name. Here is the code for both the Java classes.
Father.java
package headfirstspring;
public class Father {
private String firstName;
private String lastName;
public void showFullName(){
System.out.println("Full name is : "+getFirstName() + " " + getLastName());
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Child.java
package headfirstspring;
public class Child extends Father{
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Step 2 : Configure the beans in the config file.
In the configuration file, child bean definition should refer the parent bean with the attribute parent. In case this is not mentioned child bean will not know from where to get the value for last name and it will remain with a value null.
Step 3: Run the Test Program.
Here is the code.
package headfirstspring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestInheritance {
public static void main(String args[]){
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext("config.xml");
Father father = (Father)context.getBean("father");
father.showFullName();
Child child = (Child)context.getBean("child");
child.showFullName();
}
}
Related Posts
Inheritance Example in Spring Without Java Super Class
0 comments:
Post a Comment