Friday, 7 November 2014

Java Inheritance Examples


KANERIA DHAVAL

Exercise on Java Inheritance


Program 1:
Consider a superclass PurchaseItem which models customer’s purchases. This class has:
- two private instance variables name (String) and unitPrice (double).
- One constructor to initialize the instance variables.
- A default constructor to initialize name to “no item”, and unitPrice to 0. use this()
- A method getPrice that returns the unitPrice.
- Accessor and mutator methods.
- A toString method to return the name of the item followed by @ symbol, then the
unitPrice.
Consider two subclasses WeighedItem and CountedItem. WeighedItem has an additional instance variable weight (double) in Kg while CountedItem has an additional variable quantity (int) both private.
- Write an appropriate constructor for each of the classes making use of the constructor of the superclass in defining those of the subclasses.
- Override getPrice method that returns the price of the purchasedItem based on its unit price and weight (WeighedItem), or quantity (CountedItem). Make use of getPrice of the superclass
- Override also toString method for each class making use of the toString method of the superclass in defining those of the subclasses.
toString should return something that can be printed on the receipt.
For example:
Banana @ 3.00 1.37Kg 4.11 SR (in case of WeighedItem class)
Pens @ 4.5 10 units 45 SR (in case of CountedItem class)
Write an application class where you construct objects from the two subclasses and print them on the screen.


CountedItem.java

public class CountedItem extends PurchaseItem
{
private int quantity;
public CountedItem() {
}
public CountedItem(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}

public void setQuantity(int quantity) {
this.quantity = quantity;
}

public double getPrice()
{
return quantity*super.getPrice();
}

public String toString() {
return super.toString()+" "+quantity+"units "+getPrice()+"SR";
}
}

Program1.java

import java.util.Scanner;
public class Program1 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner scan=new Scanner(System.in);
System.out.println("=========Weighted Item============");
System.out.println("Enter Name, Unit Price, Weight :-");
WeighedItem w = new WeighedItem();
w.setData(scan.next(), scan.nextDouble());
w.setWeight(scan.nextDouble());
System.out.println(" "+w.toString());
System.out.println("=========Counted Item============");
System.out.println("Enter Name, Unit Price, Quantity :-");
CountedItem c = new CountedItem();
c.setData(scan.next(), scan.nextDouble());
c.setQuantity(scan.nextInt());
System.out.println(" "+c.toString());

}

}


PurchaseItem.java


public class PurchaseItem
{
private String name;
private double unitPrice;
public PurchaseItem() {
this.name = "No Item";
this.unitPrice = 0;
}
public PurchaseItem(String name, double unitPrice) {
this.name = name;
this.unitPrice = unitPrice;
}
public void getData() {
System.out.println("Name :- "+name);
System.out.println("Unit Price :- "+unitPrice);
}
public void setData(String name, double unitprice) {
this.name = name;
this.unitPrice=unitprice;
}
public double getPrice(){
return unitPrice;
}

public String toString() {
return name + " @ " + unitPrice ;
}
}

WeighedItem.java

public class WeighedItem extends PurchaseItem
{
private double weight;
public WeighedItem() {
}
public WeighedItem(double weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}

public void setWeight(double weight) {
this.weight = weight;
}

public double getPrice()
{
return weight*super.getPrice();
}
public String toString() {

return super.toString()+" "+weight+"kg "+getPrice()+"SR";
}
}



Program 2:
Write an employee class Janitor to accompany the other employees. Janitors work twice as many hours (80 hours/week), they make $30,000 ($10,000 less than others), they get half as much vacation (only 5 days), and they have an additional method named clean that prints "Workin' for the man."
Note: Use the super keyword to interact with the Employee superclass as appropriate.

Employee.java

public class Employee {
public int getHours() {
return 40;
}

public double getSalary() {
return 40000.0;
}

public int getVacationDays() {
return 10;
}

}


Janitor.java

public class Janitor extends Employee{
public int getHours() {
return 2 * super.getHours();
}
public double getSalary() {
return super.getSalary() - 10000.0;
}
public int getVacationDays() {
return super.getVacationDays() / 2;
}

public void clean() {
System.out.println("Workin' for the man.");
}
}


Program2.java

public class Program2 {

public Program2() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Employee e = new Employee();
Janitor j = new Janitor();
System.out.println("Employee Working Hours :- " + e.getHours());
System.out.println("Janitor Working Hours :- " + j.getHours());
System.out.println("Employee Salary :- " + e.getSalary());
System.out.println("Janitor Salary :- " + j.getSalary());

System.out.println("Employee Vacation Days : " + e.getVacationDays());
System.out.println("\n\tJanitor Vacation Days : " + j.getVacationDays());

}

}


Program 3:
Write Java code to implement the following inheritance hierarchy:
The two sub classes Student and Employee should override display() method. In Student, display() should show GPA and the other attributes in the super class. And in Employee, display() should show the job title and the other attributes in the super class.
Write a main program that should do the following:
1- Create an instant of class Student and an instant of class Employee with proper values for the attributes.
2- Display the content of each class using display() method.

Employee.java

class Employee extends Person {

private String jobtitle;
public Employee() {
// TODO Auto-generated constructor stub
}
public Employee(String jobtitle) {

this.jobtitle=jobtitle;
}

public void setData(String jobtitle) {

this.jobtitle=jobtitle;
}

public void getData() {
System.out.println("Job Title :-"+jobtitle);
}
public void display(){
super.getData();
getData();
}
}


Person.java

public class Person {

private String firstname,lastname,address;
protected int id;
public Person() {
// TODO Auto-generated constructor stub
}

public Person(String firstname, String lastname, String address,int id) {
this.firstname=firstname;
this.lastname=lastname;
this.address=address;
this.id=id;
}
public void setData(String firstname, String lastname, String address,int id) {
this.firstname=firstname;
this.lastname=lastname;
this.address=address;
this.id=id;
}
public void getData() {
System.out.println("id :- "+id);
System.out.println("First Name :- "+firstname);
System.out.println("Last Name :- "+lastname);
System.out.println("Address :- "+address);
}
public void dispaly(){
getData();
}
}

Program3.java

import java.util.Scanner;
public class Program3 {

public Program3() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner scan=new Scanner(System.in);
System.out.println("=======Student============");
Student s=new Student();
System.out.println("Enter First name, Last name, Address, Id, GPA :- ");
s.setData(scan.next(), scan.next(), scan.next(), scan.nextInt());
s.setData(scan.nextDouble());
s.display();
System.out.println("=======Employee============");
Employee e=new Employee();
System.out.println("Enter First name, Last name, Address, Id, Job Title :- ");
e.setData(scan.next(), scan.next(), scan.next(), scan.nextInt());
e.setData(scan.next());
e.display();
}

}

Student.java

class Student extends Person {

private double gpa;
/**
*
*/
public Student() {
// TODO Auto-generated constructor stub
}

public Student(double gpa) {
this.gpa=gpa;
}
public void setData(double gpa) {
this.gpa=gpa;
}
public void getData() {
System.out.println("GPA :-"+gpa);
}
public void display(){
super.getData();
getData();
}
}



Program 4:
Write a Patient class which inherits from the Person class.
You may also need to use the Money class. The Patient class requires the following:
- a variable to store the patient number for the patient
- a variable to store the hospital
- a variable to store the patient 's year of joining the hospital
- a variable to store the patient 's address
- a variable to store the medical fees that the patient pays
- constructor methods, which initialise the variables
- methods to set the hospital , year of joining and address
- methods to get the hospital, year of joining and address
- a method to calculate the medical fees : It should take a Money object (the basic fee
per year) as a parameter and use it to return the basic fee for the patient. A patient
should pay the basic fee for the year of R 1200, 50.
- a toString method

Money.java

class Money
{
private double fees;
public Money() {
// TODO Auto-generated constructor stub
fees=120050d;
}
public double getFees(){
return fees;
}
}

Patient.java

import java.sql.Date;
import java.text.SimpleDateFormat;


class Patient extends Person {

private int id,year;
private String hospital,address;
private double fees;
/**
*
*/
public Patient() {
// TODO Auto-generated constructor stub
}
public Patient(int id, String hospital, String address, int year) {

this.id=id;
this.hospital=hospital;
this.address=address;
this.year=year;
}

public void setData(int id, String hospital, String address, int year) {

this.id=id;
this.hospital=hospital;
this.address=address;
this.year=year;
}

public void getData(){
System.out.println("Id :-"+id);
System.out.println("Hospital :-"+hospital);
System.out.println("Address :-"+address);
System.out.println("Joining Year :-"+year);
}
public void getFees(Money m){
System.out.println("Fees :- "+m.getFees()*(((new java.util.Date().getYear())+1900)-year));
}

}


Program4.java

import java.util.Scanner;

public class Program4 {

/**
*
*/
public Program4() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner scan=new Scanner(System.in);
System.out.println("Enter id, Hospital, Address, year of joining :- ");
Patient p=new Patient(scan.nextInt(), scan.next(), scan.next(), scan.nextInt());
p.getData();
p.getFees(new Money());
}

}


Program 5:
Create a superclass, Student, and two subclasses, Undergrad and Grad.
The superclass Student should have the following data members: name, ID,
grade, age, and address.
The superclass, Student should have at least one method: boolean isPassed
(double grade) The purpose of the isPassed method is to take one parameter, grade (value between 0 and 100) and check whether the grade has passed the requirement for passing a course. In the Student class this method should be empty as an abstract method.
The two subclasses, Grad and Undergrad, will inherit all data members of the
Student class and override the method isPassed. For the UnderGrad class, if the
grade is above 70.0, then isPassed returns true, otherwise it returns false. For the
Grad class, if the grade is above 80.0, then isPassed returns true, otherwise
returns false.
Create a test class for your three classes. In the test class, create one Grad object
and one Undergrad object. For each object, provide a grade and display the
results of the isPassed method.

Grade.java

class Grade extends Student
{

@Override
boolean isPassed(double grade) {
// TODO Auto-generated method stub
if(grade>80)
return true;
else
return false;
}
}

Program5.java

import java.util.Scanner;

public class Program5 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner scan=new Scanner(System.in);
Grade g=new Grade();
System.out.println("=========Grade===========");
System.out.println("Enter id, name, city, age :-");
g.setData(scan.nextInt(), scan.next(), scan.next(), scan.nextInt());
System.out.println("Enter Grade :-");
if((g.isPassed(scan.nextDouble()))==true)
System.out.println("You passed the exam.");
else
System.out.println("You have not passed the exam.");
UnderGrade ug=new UnderGrade();
System.out.println("===========Undergrade============");
System.out.println("Enter id, name, city, age :-");
ug.setData(scan.nextInt(), scan.next(), scan.next(), scan.nextInt());
System.out.println("Enter Grade :-");
if((ug.isPassed(scan.nextDouble()))==true)
System.out.println("You passed the exam.");
else
System.out.println("You have not passed the exam.");
}

}


Student.java

abstract class Student
{
private String name,address;
private double grade;
private int id,age;
void setData(int id,String name,String address,int age){
this.id=id;
this.name=name;
this.age=age;
this.address=address;
}
abstract boolean isPassed(double grade);
}


Undergrade.java

class UnderGrade extends Student
{

@Override
boolean isPassed(double grade) {
// TODO Auto-generated method stub
if(grade>70)
return true;
else
return false;
}
}


2 comments:

  1. perfect explanation about java programming .its very useful.thanks for your valuable information.best java institute in chennai | best java training in velachery

    ReplyDelete
  2. Great post!I am actually getting ready to across this information, I am very happy to this commands.Also great blog here with all of the valuable information you have.Well done, it's a great knowledge.
    Software Testing Training in Chennai | Hadoop Training in Chennai

    ReplyDelete