Credits

Monday, December 28, 2009

Java's Inheritance

A parent class may pass on its data and methods to its child classes. This is the concept of Inheritance. In creating this relationship, the keyword extends is used.

See the example below for the application.


[+/-] show/hide




/**
* example of parent and child relationship
* @author Rose
*/
import java.io.*;
public class Book {
String title;
int numPages;

public void setTitle() throws Exception
{
BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Title of a book:");
title=x.readLine();}

public String getTitle()
{return title;
}
public void setNumPages() throws Exception
{
BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Number of Pages:");
numPages=Integer.parseInt(x.readLine());}

public int getNumPages()
{return numPages;
}
}


/**
*The Child Class of Parent Book
* @author Rose
*/
import java.io.*;
public class Textbook extends Book{
int gradeLevel;
public static void main(String args[]) throws Exception{

Textbook t=new Textbook();
t.setTitle();
t.setNumPages();
BufferedReader y=new BufferedReader(new InputStreamReader (System.in));
System.out.println("Enter grade level: ");
int glevel=Integer.parseInt(y.readLine());
t.setGradeLevel(glevel);
System.out.println("Book Title:"+t.getTitle());
System.out.println("Number of Pages:"+t.getNumPages());
System.out.println("Grade level:"+t.getGradeLevel());
}
void setGradeLevel(int g)
{gradeLevel=g;}
int getGradeLevel()
{return gradeLevel;}
}

AddThis