Tuesday, July 20, 2010

More of Inheritance Illustration

 To define clearly the use of inheritance,  we apply this to a relationship between a student who has to go through different schooling levels including college.

The program below assigns the Student as the parent class while College as the child class. Through inheritance, the child class can simply call the methods and fields in the parent class by any object that instantiates it.

The program below illustrates this point.

[+/-] 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();

System.out.println("object of parent class");
System.out.println("Student's name : "+obj1.getname());
System.out.println("Student'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"+obj2.name+"\n"+obj2.getaddress()+"\n"+obj2.getcourse());



class Student1{
protected String name;
protected String address;

void setname(String xname)

String getname()
{return name;}

void setaddress(String xaddress)

String getaddress()
{return address;}


class College1 extends Student1{

String course;

void setcourse(String xcourse)

String getcourse()
{return course;}


No comments: