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;
}
}


45 comments:

  1. 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
  2. Really enjoying your post, you have a great teaching style and make these new concepts much easier to understand.Thanks.
    CloudSim Training in Chennai | Core Java Training in Chennai.

    ReplyDelete
  3. Wow! Such an amazing and helpful post this is.I really really love it.It's so good and so awesome.I am just amazed. I hope that you continue to do your work like this in the future also.

    Advance Java Training in Chennai | Android Training in chennai.

    ReplyDelete
  4. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Click here:
    angularjs training in Annanagar

    ReplyDelete
  5. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Click here:
    Angularjs training in chennai


    Click here:
    angularjs training in bangalore

    Click here:
    angularjs training in online

    ReplyDelete
  6. This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.
    Click here:
    Microsoft azure training in chennai


    Click here:
    Microsoft Azure training in online

    ReplyDelete
  7. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    digital marketing training in marathahalli

    digital marketing training in rajajinagar

    Digital Marketing Training in online


    full stack developer training in pune


    full stack developer training in annanagar

    ReplyDelete
  8. Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
    full stack developer training in tambaram

    full stack developer training in velachery



    ReplyDelete
  9. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    python training institute in chennai
    python training in chennai
    python training in chennai

    ReplyDelete
  10. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    Blueprism training in Pune

    Blueprism online training

    Blue Prism Training in Pune

    ReplyDelete
  11. Appreciation for really being thoughtful and also for deciding on certain marvelous guides most people really want to be aware of.

    ReplyDelete
  12. Really you have done great job,There are may person searching about that now they will find enough resources by your post
    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  13. Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    best java training in coimbatore
    php training in coimbatore
    best php training institutes in coimbatore

    ReplyDelete
  14. Well you use a hard way for publishing, you could find much easier one!
    Well you use a hard way for publishing, you could find much easier one!
    keep update a lot.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  15. We are urgently in need of Organs Donors, Kidney donors,Female Eggs,Kidney donors Amount: $500.000.00 Dollars
    Female Eggs Amount: $500,000.00 Dollars
    WHATSAP: +91 91082 56518
    Email: : customercareunitplc@gmail.com
    Please share this post.

    ReplyDelete
  16. 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..
    oracle training in chennai

    oracle training in omr

    oracle dba training in chennai

    oracle dba training in omr

    ccna training in chennai

    ccna training in omr

    seo training in chennai

    seo training in omr


    ReplyDelete
  17. Thank you for posting informative insights, I think we have got some more information to share with! Do check out
    oracle training in chennai and let us know your thoughts. Let’s have great learning!

    ReplyDelete
  18. If AWS is a job that you're dreaming of, then we, Infycle are with you to make your dream into reality. Infycle Technologies offers the best AWS Training in Chennai, with various levels of highly demanded software courses such as Oracle, Java, Python, Hadoop, Big Data, etc., in 100% hands-on practical training with specialized tutors in the field. Along with that, the pre-interviews will be given for the candidates, so that, they can face the interviews with complete knowledge. To know more, dial 7502633633 for more.
    BEST AWS TRAINIJNG IN CHENNNAI

    ReplyDelete
  19. Train yourself in specific software modules to brush up your skills & shine in your career growth with the best software training institute in Chennai, Infycle Technologies. Infycle offers the excellent Data Science Course in Chennai to serve the candidate's job profile requirements, including the top job placements in the MNC's. Rather than just teaching the theories, our fundamental aim is to make you a master by giving you live hands-on training. Therefore, individuals will be asked to work on the live tasks & real-time use cases that bring out the definite coder in you! To grab all these, call 7502633633 for a free demoGrab Data Science Course in Chennai | Infycle Technologies

    ReplyDelete
  20. Be a part of India's fast growing institution . As our institution is providing CS executive classes and free CSEET classes . So don't waste your valuable time and contact us or visit our website at https://uniqueacademyforcommerce.com/

    ReplyDelete
  21. Reach to the best Python Training institute in Chennai for skyrocketing your career, Infycle Technologies. It is the best Software Training & Placement institute in and around Chennai, that also gives the best placement training for personality tests, interview preparation, and mock interviews for leveling up the candidate's grades to a professional level.

    ReplyDelete
  22. There Are Many Complaints About XM REVIEW Broker In The Internet But You Should Read This Review Before Investing Your Money With Them. We Have Personally Tested XM Fx And Found It To Be A Scam, Avoid Them At All Costs!

    ReplyDelete