Monday, December 6, 2010

Java's Implementation of Inheritance

The very core of object - oriented programming is reusability and this is quite illustrated in the application of inheritance.

In Java, we can create a parent and child class that can share common characteristics and functions but may also acquire individual differences.

When we create a parent - child relationship, we use the keyword extends in the class header line. With this, we then create instances of these classes and just call their methods. See the programs below for illustration.

[+/-] show/hide

import javax.swing.*;
public class SampleInheritance3{

public static void main (String args[]){
String myname=JOptionPane.showInputDialog("Input a student name: ");
String myaddress=JOptionPane.showInputDialog("Input a student's address: ");

Student1 obj1=new Student1();

JOptionPane.showMessageDialog(null,"object of parent class\n Student's name : "+obj1.getname()+"\nStudent's address : "+obj1.getaddress());

College1 obj2=new College1();
String mycourse=JOptionPane.showInputDialog("Input a student's college course: ");

JOptionPane.showMessageDialog(null,"object of the child class");
JOptionPane.showMessageDialog(null,"Student's Info: "+"\n""\n"+obj2.getaddress()+"\n"+obj2.getcourse());



//the parent class
class Student1{
protected String name;
protected String address;

void setname(String xname)

String getname()
{return name;}

void setaddress(String xaddress)

String getaddress()
{return address;}


//the child class
class College1 extends Student1{

String course;

void setcourse(String xcourse)

String getcourse()
{return course;}


No comments: