In previous post we learned about inheritance in Java programming by using simple code example. In this post we will consider another code example of inheritance in Java. In previous post we created a Car class (child class) which inherited some attributes and methods from Vehicle class (parent class). In this post we will create a Student class (child class) which will inherit attributes and methods from Human class (parent class).
[js]
//Student class code:
package learningclassesaobjects;
public class Student extends Human {
int rollNo;
public void setRollNo(int x){
rollNo = x;
}
public void getRollNo(){
System.out.printf("Your Roll No is: %dn", rollNo);
}
}
//Human class code:
package learningclassesaobjects;
public class Human {
int cnic;
public void setCNIC(int x){
cnic = x;
}
public void getCNIC(){
System.out.printf("Your CNIC is : %dn", cnic);
}
}
//Main class code:
package learningclassesaobjects;
public class Main {
public static void main(String[] args) {
Student aStudent = new Student(); //created an object of Student class
aStudent.setCNIC(1234); // called a method of Human class which is parent class of Student class
aStudent.setRollNo(3467); // called a method of Student class which is child class
aStudent.getCNIC(); // called a method of Human class which is parent class of Student class
aStudent.getRollNo(); // called a method of Student class which is child class
}
}
[/js]
Output: