SlideShare a Scribd company logo
1 of 25
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________




                          SSK 3101
          COMPUTER PROGRAMMING II

                                 LAB 4



     NAME                   : SUGENTIRAN A/L MANE

  LECTURER NAME             : DR: MOHD TAUFIK ABDULLAH




                                     1
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________
           Fakulti Sains Komputer dan Teknologi Maklumat
                SSK3101 (Programming Computer II)
                        Semester 1 2011/2012
                           October 21, 2010

                                    Lab 4 (Individual)

Learning Objective:
The objective of this lab is to
   1. Construct An Object-oriented Program Using Generic Programming (P4)

Instructions:
    1. Date of submission is 28.10.2011 and submits to the lecturer the UML, source program and
       the output. Good code development (which uses appropriate selection of variable name,
       proper declaration, comments, indentation, and etc.) Your program must be successfully
       demonstrates to the demonstrator.
    2. Copy or other forms of cheating is forbidden. The faculty has very strong rules about this, and
       the penalties may be severe. The standard penalty for the first offence is to award 0 to all
       parties concerned.




                                                  2
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________
Question 1                                                                               [10M]

We had two inherited classes which are Person and Student from Lab 2 questions. Add class named
Employee. Make Faculty and Staff subclasses of Employee. An employee has an office, salary and
date-hired. Define a class named MyDate that contains the fields year, month and day. A faculty
member has office hours and a rank. A staff member has a title. Override the toString method in
each class to display the class name and the person’s name.

Draw the UML diagram for the classes. Implement the classes. Write a class to test program that
creates a Person, Student, Employee, Faculty and Staff and invokes their toString() methods.


Question 2                                                                               [10M]

In class (define on your own, example class name that contain main method can be
TestPolymorphismDemo) that contains main method, construct a method Print(Object O). By
using polymorphism feature, write the code which pass the instances of Person, Student, Employee,
Faculty and Staff to Print(Object O) method which invokes their respective toString() method.


Question 3                                                                               [10M]

Extend the Staff class to Admin class and Lecturer class. Lecturer has room_no and subject.
Variable room_no and subject should be declared by using a suitable modifier to restrict its
accessibility within the class itself. The variables can only be achieved by using method getRoom()
and getSubject().

Implement toString() methods in both Admin and Lecturer classes. For Admin class, toString()
method will print out the class name. For Lecturer, toString() method will print out the room_no
and subject. Just assign any random string value to room_no and subject.

Construct a method known as PrintDetails(Object O) in the Staff class. Pass both instances of
Admin and Lecturer to PrintDetails method and invoke their respective toString() method by using
the operator “instanceof” and appropriate casting might be required.


Question 4                                                                               [10M]

Rewrite the code in Question 2 without using polymorphism feature by using any programming
method, skill and creativity that you have to achieve the exact same output.


Explain the advantage of using polymorphism feature in the coding.




                                                 3
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________



      Question 1

      UML:-
                                      Person

                       +firstName:String
                       +lastName:String
                       +streetAddress:String
                       +zipCode:int
                       +phoneNumber:int

                       +Person()
                       +Person(String,String,String,int,int)
                       +setFirstName():void
                       +getFirstName(String)
                       +setLirstName():void
                       +getLirstName(String)
                       +setStreetAddress():void
                       +getStreetAddress(String)
                       +setZipCode():void
                       +getZipCode(int)
                       +setPhoneNumber():void
                       +setPhoneNumber(int)
                       +toString():String




                                    Student

                     +majorField:String
                     +gradePointAverage:String

                     +Student()
                     +Student(String,String)
                     + setMajorField ():void
                     +get MajorField (String)
                     +setGradePointAverage ():void
                     +getGradePointAverage (String)
                     +toString():String




                                           4
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________




                       Employee

          +office:String
          +date:String                                                MyDate
          +salary:double
                                                      +year:int
          + Employee()                                +day:int
          + Employee(String,String,double)            +month:String
          +setOffice():void
          +getOffice(String)                          + MyDate()
          +setSalary():void                           + MyDate(int,String,int)
          +getSalary(double)                          +toString():String
          +setDataHired():void
          +getDataHired(String)
          +toString():String




                                                                 Staff
                  Faculty
                                                 +title:String
    +officeHours1:String
    +officeHours2:String                         + Staff()
    +rank:String                                 + Staff(String)
                                                 +setTitle():void
    + Faculty()                                  +getTitle(String)
    + Faculty(int,int,String)                    +toString():String
    +setOfficeHours1():void
    +getOfficeHours1(int)
    +setOfficeHours2():void
    +getOfficeHours2(int)
    +setRank():void
    +getRank(String)
    +toString():String




                                             5
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________

      Coding:-

Class Person


public class Person {
      String firstName, lastName, streetAddress;
      int zipCode, phoneNumber;
      Person(){

      }
      Person(String firstName,String lastName,String streetAddress,int zipCode,int
      phoneNumber){
             this.firstName=firstName;
             this.lastName=lastName;
             this.streetAddress=streetAddress;
             this.zipCode=zipCode;
             this.phoneNumber=phoneNumber;

      }

      public void setFirstName(String firstName){
             this.firstName=firstName;
      }

      public String getFirstName(){
             return firstName;
      }

      public void setLastName(String lastName){
             this.lastName=lastName;
      }

      public String getLastName(){
             return lastName;
      }

      public void setStreetAddress(String streetAddress){
             this.streetAddress=streetAddress;
      }

      public String getStreetAddress(){
             return streetAddress;
      }

      public void setZipCode(int zipCode){
             this.zipCode=zipCode;
      }

      public int getZipCode(){
             return zipCode;
      }



                                             6
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________

      public void setPhoneNumber(int phoneNumber){
             this.phoneNumber=phoneNumber;
      }

      public int getPhoneNumber(){
             return phoneNumber;
      }

      public String toString(){
             return "First Name : "+getFirstName()+"nLast Name : "+getLastName()
             +"nStreet Addrees : "+getStreetAddress()+"nZip Code : "+getZipCode()
             +"nPhone Number : "+getPhoneNumber();
      }
}

----------------------------------------------

Class Student

public class Student extends Person{
       String majorField,gradePointAverage;

      Student(){

      }

      Student(String majorField, String gradePointAverage){
             //super(firstName,lastName,streetAddress,zipCode,phoneNumber);
             this.majorField=majorField;
             this.gradePointAverage=gradePointAverage;

      }

      public void setMajorField(String majorField){
             this.majorField=majorField;
      }

      public String getMajorField(){
             return majorField;
      }

      public void setGradePointAverage(String gradePointAverage){
             this.gradePointAverage=gradePointAverage;
      }

      public String getGradePointAverage(){
             return gradePointAverage;
      }

      public String toString(){
             return "Major Field : "+getMajorField()+"nGrade Point Average :
             "+getGradePointAverage();
      }
}


                                              7
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________

------------------------------------------


Class Employee

public class Employee {
       String office,date;
       double salary;

      Employee(){
      }

      Employee(String office, double salary, String date){
             this.office=office;
             this.salary=salary;
             this.date=date;
      }

      public void setOffice(String office){
             this.office=office;
      }

      public String getOffice(){
             return office;
      }

      public void setSalary(double salary){
             this.salary=salary;
      }

      public double getSalary(){
             return salary;
      }

      public void setDateHired(String date){
             this.date=date;
      }

      public String getDateHired(){
             return date;
      }

      public String toString(){
             return "Office : "+getOffice()+"nSalary : Rm "+getSalary()+"nDate Hired :
             "+getDateHired();
      }
}


Class Staff

public class Staff extends Employee{
       String title;




                                              8
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________
      Staff(){
      }

      Staff(String title){
             this.title=title;
      }

      public void setTitle(String title){
             this.title=title;
      }

      public String getTitle(){
             return title;
      }

      public String toString(){
             return "Title : "+getTitle();
      }
}

---------------------------------------

Class Faculty

public class Faculty extends Employee{
       int officeHours1,officeHours2;
       String rank;

      Faculty(){
      }

      Faculty(int officeHours1,int officeHours2, String rank){
             //super(office,salary,date);
             this.officeHours1=officeHours1;
             this.officeHours2=officeHours2;
             this.rank=rank;

      }

      public void setOfficeHours1(int officeHours1){
             this.officeHours1=officeHours1;
      }

      public int getOfficeHours1(){
             return officeHours1;
      }

      public void setOfficeHours2(int officeHours2){
             this.officeHours2=officeHours2;
      }

      public int getOfficeHours2(){
             return officeHours2;
      }




                                             9
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________
      public void setRank(String rank){
             this.rank=rank;
      }

      public String getRank(){
             return rank;
      }

      public String toString(){
             return "Office Hours : "+getOfficeHours1()+"am to "+getOfficeHours2()
             +"pm"+"nRank : "+getRank();
      }

}

---------------------------------------------------

Class MyDate

public class MyDate {
       int year,day;
       String month;

      MyDate(){
      }

      MyDate(int year,String month,int day){
             this.year=year;
             this.month=month;
             this.day=day;
      }

      public String toString(){
             return "Date Hired : "+day+"/"+month+"/"+year;
      }
}

-----------------------------------------------------


Class TestQ1

import java.util.*;
public class TestQ1 {
public static void main(String[] args) {
       String ans;
       do
       {
       int a;
       Scanner scan=new Scanner(System.in);
       System.out.println("Enter 1 for Student and 2 for Staff : ");
       a=scan.nextInt();

      if(a==1)
      {


                                           10
SSK 3101 – LAB 4                                                     Semester 1
2011/2012
____________________________________________________________________________
             //Class Person
             String first,last,add;
             int zip,phone;
             System.out.print("First Name :");
             first=scan.next();
             System.out.print("Last Name : ");
             last=scan.next();
             System.out.print("Address : ");
             add=scan.next();
             System.out.print("Zip Code : ");
             zip=scan.nextInt();
             System.out.print("Phone No : ");
             phone=scan.nextInt();
             Person person=new Person(first,last,add,zip,phone);
             System.out.println("***************************"+"nClass Person");
             System.out.println(person.toString());
             System.out.println("***************************");
             //Class Student
             String major,point;
             System.out.print("Major Field : ");
             major=scan.next();
             System.out.print("Grade Point Average : ");
             point=scan.next();
             Student student=new Student(major,point);
             System.out.println("***************************"+"nClass Student");
             System.out.println(student.toString());
             System.out.println("***************************");
      }
      else if(a==2)
      {
             //Class Employee
             String office;
             double salary;
             int day,year;
             String month;
             System.out.println("Office Name : ");
             office=scan.next();
             System.out.println("Salary : ");
             salary=scan.nextDouble();
             System.out.println("Date Hired (mm/dd/yyyy) : ");
             System.out.println("Month");
             month=scan.next();
             System.out.println("Day");
             day=scan.nextInt();
             System.out.println("Year");
             year=scan.nextInt();
             MyDate date=new MyDate(year,month,day);
             date.toString();
             Employee employee=new Employee(office,salary,date.toString());
             System.out.println("**************************"+"nClass Employee");
             System.out.println(employee.toString());
             System.out.println("***************************");
             //Class Faculty
             int officeHours1,officeHours2;
             String rank;


                                       11
SSK 3101 – LAB 4                                                     Semester 1
2011/2012
____________________________________________________________________________
             System.out.println("Office Hours : ");
             officeHours1=scan.nextInt();
             System.out.println("to");
             officeHours2=scan.nextInt();
             System.out.println("Rank : ");
             rank=scan.next();
             Faculty faculty=new Faculty(officeHours1,officeHours2,rank);
             System.out.println("***************************"+"nClass Faculty");
             System.out.println(faculty.toString());
             System.out.println("***************************");
             //Class Staff
             String title;
             System.out.println("Title : ");
             title=scan.next();
             Staff staff=new Staff(title);
             System.out.println("***************************"+"nClass Staff");
             System.out.println(staff.toString());
             System.out.println("***************************");
      }
      System.out.println("Do it again (Y/N)?");
      ans=scan.next();
      }while(ans.equalsIgnoreCase("Y"));

      }
}




      Input:-




                                       12
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________
      Output:-




      Question 2:-


                                     13
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________

import java.util.*;
public class TestPolymorphismDemo {
       public static void main(String[] args) {
              String ans;

             do {

             int a;
             Scanner scan=new Scanner(System.in);
             System.out.println("Enter 1 for Student and 2 for Staff : ");
             a=scan.nextInt();

             if(a==1){
             //Class Person
             String first,last,add;
             int zip,phone;
             System.out.print("First Name :");
             first=scan.next();
             System.out.print("Last Name : ");
             last=scan.next();
             System.out.print("Address : ");
             add=scan.next();
             System.out.print("Zip Code : ");
             zip=scan.nextInt();
             System.out.print("Phone No : ");
             phone=scan.nextInt();
             System.out.println("***************************"+"nClass Person");
             Print(new Person(first,last,add,zip,phone));
             System.out.println("***************************");
             //Class Student
             String major,point;
             System.out.print("Major Field : ");
             major=scan.next();
             System.out.print("Grade Point Average : ");
             point=scan.next();
             System.out.println("***************************"+"nClass Student");
             Print(new Student(major,point));
             System.out.println("***************************");
             }
             //Class Employee
             else if(a==2){
             String office;
             double salary;
             int day,year;
             String month;
             System.out.println("Office Name : ");
             office=scan.next();
             System.out.println("Salary : ");
             salary=scan.nextDouble();
             System.out.println("Date Hired (mm/dd/yyyy) : ");
             System.out.println("Month");
             month=scan.next();
             System.out.println("Day");
             day=scan.nextInt();


                                           14
SSK 3101 – LAB 4                                                     Semester 1
2011/2012
____________________________________________________________________________
             System.out.println("Year");
             year=scan.nextInt();
             MyDate date=new MyDate(year,month,day);
             date.toString();
             System.out.println("**************************"+"nClass Employee");
             Print(new Employee(office,salary,date.toString()));
             System.out.println("***************************");
             //Class Faculty
             int officeHours1,officeHours2;
             String rank;
             System.out.println("Office Hours : ");
             officeHours1=scan.nextInt();
             System.out.println("to");
             officeHours2=scan.nextInt();
             System.out.println("Rank : ");
             rank=scan.next();
             System.out.println("***************************"+"nClass Faculty");
             Print(new Faculty(officeHours1,officeHours2,rank));
             System.out.println("***************************");
             //Class Staff
             String title;
             System.out.println("Title : ");
             title=scan.next();
             System.out.println("***************************"+"nClass Staff");
             Print(new Staff(title));
             System.out.println("***************************");
             //Print(new Object());
             }
             System.out.println("Do it again (Y/N)?");
             ans=scan.next();

             } while (ans.equalsIgnoreCase("Y"));
      }
      public static void Print(Object o){
             System.out.println(o.toString());
      }
}


      Input:-




      Output:-



                                           15
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________




Question 3:-


                                     16
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________

UML:-




                                      Lecturer
                Admin
                                                                    Staff
                              +roon_no:String
        +Admin()              +subject:String
        +toString():String
                                                           PrintDetails():void
                              + Lecturer()
                              + Lecturer(String,String)
                              +setRoomNo():void
                              +getRoomNo(String)
                              +setSubject():void
                              +getSubject(String)
                              +toString():String




Coding:-


                                      17
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________

Class Admin

public class Admin {
       public Admin(){
       }

      public String toString(){
             return "Class Admin";
      }
}

-------------------------------------------------

Class Lecturer

public class Lecturer {
       String room_no,subject;

      public Lecturer(){
      }

      public Lecturer(String room_no,String subject){
             this.room_no=room_no;
             this.subject=subject;
      }

      public void setRoomNo(String newRoom_No){
             this.room_no=newRoom_No;
      }

      public String getRoomNo(){
             return room_no;
      }

      public void setSubject(String newSubject){
             this.subject=newSubject;
      }

      public String getSubject(){
             return subject;
      }

      public String toString(){
             return "Room No : "+room_no+"nSubject : "+subject;
      }

}




Class Staff


                                           18
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________

public class Staff {
       public static void PrintDetails(Object o){
              if (o instanceof Admin){
               System.out.println(((Admin)o).toString()+"n***************************");
           }
              else if (o instanceof Lecturer){
               System.out.println(((Lecturer)o).toString()
+"n***************************");
           }
       }
}

----------------------------------------

Class TestStaff

import java.util.*;
public class TestStaff {
       public static void main(String[] args) {
              Scanner scan=new Scanner(System.in);
              Staff staff=new Staff();

              //Class Admin
              //Use casting
              Object admin=new Admin();
              System.out.println("***************************");
              staff.PrintDetails(admin);

              //Class Lecturer
              String room_no,subject;
              System.out.print("Room No : ");
              room_no=scan.next();
              System.out.print("Subject : ");
              subject=scan.next();
              System.out.println("***************************");
              staff.PrintDetails(new Lecturer(room_no,subject));
          }
}


Input:-




                                            19
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________




Output:-




       Question 4:-



                                     20
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________
import java.util.*;
public class TestQ4 {
       public static void main(String[] args) {
       String ans;

     do {
     int a;
     Scanner scan=new Scanner(System.in);
     System.out.println("Enter 1 for Student and 2 for Staff : ");
     a=scan.nextInt();

     if(a==1){
            //Class Person
            Person person=new Person();
            String first,last,add;
            int zip,phone;
            System.out.print("First Name :");
            first=scan.next();
            System.out.print("Last Name : ");
            last=scan.next();
            System.out.print("Address : ");
            add=scan.next();
            System.out.print("Zip Code : ");
            zip=scan.nextInt();
            System.out.print("Phone No : ");
            phone=scan.nextInt();
            person.setFirstName(first);
            person.setLastName(last);
            person.setStreetAddress(add);
            person.setZipCode(zip);
            person.setPhoneNumber(phone);
            System.out.println("***************************"+"nClass Person");
            System.out.println(person.toString());
            System.out.println("***************************");
            //Class Student
            Student student=new Student();
            String major,point;
            System.out.print("Major Field : ");
            major=scan.next();
            System.out.print("Grade Point Average : ");
            point=scan.next();
            student.setMajorField(major);
            student.setGradePointAverage(point);
            System.out.println("***************************"+"nClass Student");
            System.out.println(student.toString());
            System.out.println("***************************");
     }

     else if(a==2)
     {
            //Class Employee
            Employee employee=new Employee();
            String office;
            double salary;
            int day,year;


                                          21
SSK 3101 – LAB 4                                                     Semester 1
2011/2012
____________________________________________________________________________
             String month;
             System.out.println("Office Name : ");
             office=scan.next();
             System.out.println("Salary : ");
             salary=scan.nextDouble();
             System.out.println("Date Hired (mm/dd/yyyy) : ");
             System.out.println("Month");
             month=scan.next();
             System.out.println("Day");
             day=scan.nextInt();
             System.out.println("Year");
             year=scan.nextInt();
             MyDate date=new MyDate(year,month,day);
             date.toString();
             employee.setOffice(office);
             employee.setSalary(salary);
             employee.setDateHired(date.toString());
             System.out.println("**************************"+"nClass Employee");
             System.out.println(employee.toString());
             System.out.println("***************************");
             //Class Faculty
             Faculty faculty=new Faculty();
             int officeHours1,officeHours2;
             String rank;
             System.out.println("Office Hours : ");
             officeHours1=scan.nextInt();
             System.out.println("to");
             officeHours2=scan.nextInt();
             System.out.println("Rank : ");
             rank=scan.next();
             faculty.setOfficeHours1(officeHours1);
             faculty.setOfficeHours2(officeHours2);
             faculty.setRank(rank);
             System.out.println("***************************"+"nClass Faculty");
             System.out.println(faculty.toString());
             System.out.println("***************************");
             //Class Staff
             Staff staff=new Staff();
             String title;
             System.out.println("Title : ");
             title=scan.next();
             staff.setTitle(title);
             System.out.println("***************************"+"nClass Staff");
             System.out.println(staff.toString());
             System.out.println("***************************");
             //Print(new Object());
      }
      System.out.println("Do it again (Y/N)?");
      ans=scan.next();
      } while (ans.equalsIgnoreCase("Y"));
}
}




                                       22
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________



      Input:-




      Output:-



                                     23
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________




                                     24
SSK 3101 – LAB 4                                            Semester 1
2011/2012
____________________________________________________________________________
      Kelebihan polymorphism

1.   Code that is more dynamic at runtime
2.   Code is more flexible and reusable
3.   Code re-usability: Using the code written somewhere in program
4.   Multiple forms of one object are called in the same way




                                              25

More Related Content

What's hot

Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism JavaM. Raihan
 
Practical OOP In Java
Practical OOP In JavaPractical OOP In Java
Practical OOP In Javawiradikusuma
 
the Concept of Object-Oriented Programming
the Concept of Object-Oriented Programmingthe Concept of Object-Oriented Programming
the Concept of Object-Oriented ProgrammingAida Ramlan II
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
Concept of OOPS with real life examples
Concept of OOPS with real life examplesConcept of OOPS with real life examples
Concept of OOPS with real life examplesNeha Sharma
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxShahinAhmed49
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In JavaManish Sahu
 
Haskell study 14
Haskell study 14Haskell study 14
Haskell study 14Nam Hyeonuk
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in JavaRavi_Kant_Sahu
 

What's hot (20)

Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Java arrays
Java arraysJava arrays
Java arrays
 
Practical OOP In Java
Practical OOP In JavaPractical OOP In Java
Practical OOP In Java
 
the Concept of Object-Oriented Programming
the Concept of Object-Oriented Programmingthe Concept of Object-Oriented Programming
the Concept of Object-Oriented Programming
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Concept of OOPS with real life examples
Concept of OOPS with real life examplesConcept of OOPS with real life examples
Concept of OOPS with real life examples
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptx
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Haskell study 14
Haskell study 14Haskell study 14
Haskell study 14
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 

Similar to Lab 4 jawapan (sugentiran mane)

[C++ korea] effective modern c++ study item 5 prefer auto to explicit type de...
[C++ korea] effective modern c++ study item 5 prefer auto to explicit type de...[C++ korea] effective modern c++ study item 5 prefer auto to explicit type de...
[C++ korea] effective modern c++ study item 5 prefer auto to explicit type de...Giyeon Bang
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1Daman Toor
 
HELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdfHELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdffatoryoutlets
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210Mahmoud Samir Fayed
 
Java™ (OOP) - Chapter 10: "Thinking in Objects"
Java™ (OOP) - Chapter 10: "Thinking in Objects"Java™ (OOP) - Chapter 10: "Thinking in Objects"
Java™ (OOP) - Chapter 10: "Thinking in Objects"Gouda Mando
 
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 Mahmoud Samir Fayed
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docxjosies1
 
First compile all the classes.But to run the program we have to run .pdf
First compile all the classes.But to run the program we have to run .pdfFirst compile all the classes.But to run the program we have to run .pdf
First compile all the classes.But to run the program we have to run .pdfaoneonlinestore1
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Codemotion
 
The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31Mahmoud Samir Fayed
 
My code is not matching up with the results.The output for the cod.pdf
My code is not matching up with the results.The output for the cod.pdfMy code is not matching up with the results.The output for the cod.pdf
My code is not matching up with the results.The output for the cod.pdfsolimankellymattwe60
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88Mahmoud Samir Fayed
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202Mahmoud Samir Fayed
 

Similar to Lab 4 jawapan (sugentiran mane) (20)

Exercise2 java
Exercise2 javaExercise2 java
Exercise2 java
 
[C++ korea] effective modern c++ study item 5 prefer auto to explicit type de...
[C++ korea] effective modern c++ study item 5 prefer auto to explicit type de...[C++ korea] effective modern c++ study item 5 prefer auto to explicit type de...
[C++ korea] effective modern c++ study item 5 prefer auto to explicit type de...
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1
 
HELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdfHELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdf
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
 
newsql
newsqlnewsql
newsql
 
Java™ (OOP) - Chapter 10: "Thinking in Objects"
Java™ (OOP) - Chapter 10: "Thinking in Objects"Java™ (OOP) - Chapter 10: "Thinking in Objects"
Java™ (OOP) - Chapter 10: "Thinking in Objects"
 
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 
First compile all the classes.But to run the program we have to run .pdf
First compile all the classes.But to run the program we have to run .pdfFirst compile all the classes.But to run the program we have to run .pdf
First compile all the classes.But to run the program we have to run .pdf
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
Refactoring
RefactoringRefactoring
Refactoring
 
The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31
 
My code is not matching up with the results.The output for the cod.pdf
My code is not matching up with the results.The output for the cod.pdfMy code is not matching up with the results.The output for the cod.pdf
My code is not matching up with the results.The output for the cod.pdf
 
The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84The Ring programming language version 1.2 book - Part 78 of 84
The Ring programming language version 1.2 book - Part 78 of 84
 
The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
L10
L10L10
L10
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202
 
L4_SQL.pdf
L4_SQL.pdfL4_SQL.pdf
L4_SQL.pdf
 

Lab 4 jawapan (sugentiran mane)

  • 1. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ SSK 3101 COMPUTER PROGRAMMING II LAB 4 NAME : SUGENTIRAN A/L MANE LECTURER NAME : DR: MOHD TAUFIK ABDULLAH 1
  • 2. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Fakulti Sains Komputer dan Teknologi Maklumat SSK3101 (Programming Computer II) Semester 1 2011/2012 October 21, 2010 Lab 4 (Individual) Learning Objective: The objective of this lab is to 1. Construct An Object-oriented Program Using Generic Programming (P4) Instructions: 1. Date of submission is 28.10.2011 and submits to the lecturer the UML, source program and the output. Good code development (which uses appropriate selection of variable name, proper declaration, comments, indentation, and etc.) Your program must be successfully demonstrates to the demonstrator. 2. Copy or other forms of cheating is forbidden. The faculty has very strong rules about this, and the penalties may be severe. The standard penalty for the first offence is to award 0 to all parties concerned. 2
  • 3. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Question 1 [10M] We had two inherited classes which are Person and Student from Lab 2 questions. Add class named Employee. Make Faculty and Staff subclasses of Employee. An employee has an office, salary and date-hired. Define a class named MyDate that contains the fields year, month and day. A faculty member has office hours and a rank. A staff member has a title. Override the toString method in each class to display the class name and the person’s name. Draw the UML diagram for the classes. Implement the classes. Write a class to test program that creates a Person, Student, Employee, Faculty and Staff and invokes their toString() methods. Question 2 [10M] In class (define on your own, example class name that contain main method can be TestPolymorphismDemo) that contains main method, construct a method Print(Object O). By using polymorphism feature, write the code which pass the instances of Person, Student, Employee, Faculty and Staff to Print(Object O) method which invokes their respective toString() method. Question 3 [10M] Extend the Staff class to Admin class and Lecturer class. Lecturer has room_no and subject. Variable room_no and subject should be declared by using a suitable modifier to restrict its accessibility within the class itself. The variables can only be achieved by using method getRoom() and getSubject(). Implement toString() methods in both Admin and Lecturer classes. For Admin class, toString() method will print out the class name. For Lecturer, toString() method will print out the room_no and subject. Just assign any random string value to room_no and subject. Construct a method known as PrintDetails(Object O) in the Staff class. Pass both instances of Admin and Lecturer to PrintDetails method and invoke their respective toString() method by using the operator “instanceof” and appropriate casting might be required. Question 4 [10M] Rewrite the code in Question 2 without using polymorphism feature by using any programming method, skill and creativity that you have to achieve the exact same output. Explain the advantage of using polymorphism feature in the coding. 3
  • 4. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Question 1 UML:- Person +firstName:String +lastName:String +streetAddress:String +zipCode:int +phoneNumber:int +Person() +Person(String,String,String,int,int) +setFirstName():void +getFirstName(String) +setLirstName():void +getLirstName(String) +setStreetAddress():void +getStreetAddress(String) +setZipCode():void +getZipCode(int) +setPhoneNumber():void +setPhoneNumber(int) +toString():String Student +majorField:String +gradePointAverage:String +Student() +Student(String,String) + setMajorField ():void +get MajorField (String) +setGradePointAverage ():void +getGradePointAverage (String) +toString():String 4
  • 5. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Employee +office:String +date:String MyDate +salary:double +year:int + Employee() +day:int + Employee(String,String,double) +month:String +setOffice():void +getOffice(String) + MyDate() +setSalary():void + MyDate(int,String,int) +getSalary(double) +toString():String +setDataHired():void +getDataHired(String) +toString():String Staff Faculty +title:String +officeHours1:String +officeHours2:String + Staff() +rank:String + Staff(String) +setTitle():void + Faculty() +getTitle(String) + Faculty(int,int,String) +toString():String +setOfficeHours1():void +getOfficeHours1(int) +setOfficeHours2():void +getOfficeHours2(int) +setRank():void +getRank(String) +toString():String 5
  • 6. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Coding:- Class Person public class Person { String firstName, lastName, streetAddress; int zipCode, phoneNumber; Person(){ } Person(String firstName,String lastName,String streetAddress,int zipCode,int phoneNumber){ this.firstName=firstName; this.lastName=lastName; this.streetAddress=streetAddress; this.zipCode=zipCode; this.phoneNumber=phoneNumber; } public void setFirstName(String firstName){ this.firstName=firstName; } public String getFirstName(){ return firstName; } public void setLastName(String lastName){ this.lastName=lastName; } public String getLastName(){ return lastName; } public void setStreetAddress(String streetAddress){ this.streetAddress=streetAddress; } public String getStreetAddress(){ return streetAddress; } public void setZipCode(int zipCode){ this.zipCode=zipCode; } public int getZipCode(){ return zipCode; } 6
  • 7. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ public void setPhoneNumber(int phoneNumber){ this.phoneNumber=phoneNumber; } public int getPhoneNumber(){ return phoneNumber; } public String toString(){ return "First Name : "+getFirstName()+"nLast Name : "+getLastName() +"nStreet Addrees : "+getStreetAddress()+"nZip Code : "+getZipCode() +"nPhone Number : "+getPhoneNumber(); } } ---------------------------------------------- Class Student public class Student extends Person{ String majorField,gradePointAverage; Student(){ } Student(String majorField, String gradePointAverage){ //super(firstName,lastName,streetAddress,zipCode,phoneNumber); this.majorField=majorField; this.gradePointAverage=gradePointAverage; } public void setMajorField(String majorField){ this.majorField=majorField; } public String getMajorField(){ return majorField; } public void setGradePointAverage(String gradePointAverage){ this.gradePointAverage=gradePointAverage; } public String getGradePointAverage(){ return gradePointAverage; } public String toString(){ return "Major Field : "+getMajorField()+"nGrade Point Average : "+getGradePointAverage(); } } 7
  • 8. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ ------------------------------------------ Class Employee public class Employee { String office,date; double salary; Employee(){ } Employee(String office, double salary, String date){ this.office=office; this.salary=salary; this.date=date; } public void setOffice(String office){ this.office=office; } public String getOffice(){ return office; } public void setSalary(double salary){ this.salary=salary; } public double getSalary(){ return salary; } public void setDateHired(String date){ this.date=date; } public String getDateHired(){ return date; } public String toString(){ return "Office : "+getOffice()+"nSalary : Rm "+getSalary()+"nDate Hired : "+getDateHired(); } } Class Staff public class Staff extends Employee{ String title; 8
  • 9. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Staff(){ } Staff(String title){ this.title=title; } public void setTitle(String title){ this.title=title; } public String getTitle(){ return title; } public String toString(){ return "Title : "+getTitle(); } } --------------------------------------- Class Faculty public class Faculty extends Employee{ int officeHours1,officeHours2; String rank; Faculty(){ } Faculty(int officeHours1,int officeHours2, String rank){ //super(office,salary,date); this.officeHours1=officeHours1; this.officeHours2=officeHours2; this.rank=rank; } public void setOfficeHours1(int officeHours1){ this.officeHours1=officeHours1; } public int getOfficeHours1(){ return officeHours1; } public void setOfficeHours2(int officeHours2){ this.officeHours2=officeHours2; } public int getOfficeHours2(){ return officeHours2; } 9
  • 10. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ public void setRank(String rank){ this.rank=rank; } public String getRank(){ return rank; } public String toString(){ return "Office Hours : "+getOfficeHours1()+"am to "+getOfficeHours2() +"pm"+"nRank : "+getRank(); } } --------------------------------------------------- Class MyDate public class MyDate { int year,day; String month; MyDate(){ } MyDate(int year,String month,int day){ this.year=year; this.month=month; this.day=day; } public String toString(){ return "Date Hired : "+day+"/"+month+"/"+year; } } ----------------------------------------------------- Class TestQ1 import java.util.*; public class TestQ1 { public static void main(String[] args) { String ans; do { int a; Scanner scan=new Scanner(System.in); System.out.println("Enter 1 for Student and 2 for Staff : "); a=scan.nextInt(); if(a==1) { 10
  • 11. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ //Class Person String first,last,add; int zip,phone; System.out.print("First Name :"); first=scan.next(); System.out.print("Last Name : "); last=scan.next(); System.out.print("Address : "); add=scan.next(); System.out.print("Zip Code : "); zip=scan.nextInt(); System.out.print("Phone No : "); phone=scan.nextInt(); Person person=new Person(first,last,add,zip,phone); System.out.println("***************************"+"nClass Person"); System.out.println(person.toString()); System.out.println("***************************"); //Class Student String major,point; System.out.print("Major Field : "); major=scan.next(); System.out.print("Grade Point Average : "); point=scan.next(); Student student=new Student(major,point); System.out.println("***************************"+"nClass Student"); System.out.println(student.toString()); System.out.println("***************************"); } else if(a==2) { //Class Employee String office; double salary; int day,year; String month; System.out.println("Office Name : "); office=scan.next(); System.out.println("Salary : "); salary=scan.nextDouble(); System.out.println("Date Hired (mm/dd/yyyy) : "); System.out.println("Month"); month=scan.next(); System.out.println("Day"); day=scan.nextInt(); System.out.println("Year"); year=scan.nextInt(); MyDate date=new MyDate(year,month,day); date.toString(); Employee employee=new Employee(office,salary,date.toString()); System.out.println("**************************"+"nClass Employee"); System.out.println(employee.toString()); System.out.println("***************************"); //Class Faculty int officeHours1,officeHours2; String rank; 11
  • 12. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ System.out.println("Office Hours : "); officeHours1=scan.nextInt(); System.out.println("to"); officeHours2=scan.nextInt(); System.out.println("Rank : "); rank=scan.next(); Faculty faculty=new Faculty(officeHours1,officeHours2,rank); System.out.println("***************************"+"nClass Faculty"); System.out.println(faculty.toString()); System.out.println("***************************"); //Class Staff String title; System.out.println("Title : "); title=scan.next(); Staff staff=new Staff(title); System.out.println("***************************"+"nClass Staff"); System.out.println(staff.toString()); System.out.println("***************************"); } System.out.println("Do it again (Y/N)?"); ans=scan.next(); }while(ans.equalsIgnoreCase("Y")); } } Input:- 12
  • 13. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Output:- Question 2:- 13
  • 14. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ import java.util.*; public class TestPolymorphismDemo { public static void main(String[] args) { String ans; do { int a; Scanner scan=new Scanner(System.in); System.out.println("Enter 1 for Student and 2 for Staff : "); a=scan.nextInt(); if(a==1){ //Class Person String first,last,add; int zip,phone; System.out.print("First Name :"); first=scan.next(); System.out.print("Last Name : "); last=scan.next(); System.out.print("Address : "); add=scan.next(); System.out.print("Zip Code : "); zip=scan.nextInt(); System.out.print("Phone No : "); phone=scan.nextInt(); System.out.println("***************************"+"nClass Person"); Print(new Person(first,last,add,zip,phone)); System.out.println("***************************"); //Class Student String major,point; System.out.print("Major Field : "); major=scan.next(); System.out.print("Grade Point Average : "); point=scan.next(); System.out.println("***************************"+"nClass Student"); Print(new Student(major,point)); System.out.println("***************************"); } //Class Employee else if(a==2){ String office; double salary; int day,year; String month; System.out.println("Office Name : "); office=scan.next(); System.out.println("Salary : "); salary=scan.nextDouble(); System.out.println("Date Hired (mm/dd/yyyy) : "); System.out.println("Month"); month=scan.next(); System.out.println("Day"); day=scan.nextInt(); 14
  • 15. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ System.out.println("Year"); year=scan.nextInt(); MyDate date=new MyDate(year,month,day); date.toString(); System.out.println("**************************"+"nClass Employee"); Print(new Employee(office,salary,date.toString())); System.out.println("***************************"); //Class Faculty int officeHours1,officeHours2; String rank; System.out.println("Office Hours : "); officeHours1=scan.nextInt(); System.out.println("to"); officeHours2=scan.nextInt(); System.out.println("Rank : "); rank=scan.next(); System.out.println("***************************"+"nClass Faculty"); Print(new Faculty(officeHours1,officeHours2,rank)); System.out.println("***************************"); //Class Staff String title; System.out.println("Title : "); title=scan.next(); System.out.println("***************************"+"nClass Staff"); Print(new Staff(title)); System.out.println("***************************"); //Print(new Object()); } System.out.println("Do it again (Y/N)?"); ans=scan.next(); } while (ans.equalsIgnoreCase("Y")); } public static void Print(Object o){ System.out.println(o.toString()); } } Input:- Output:- 15
  • 16. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Question 3:- 16
  • 17. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ UML:- Lecturer Admin Staff +roon_no:String +Admin() +subject:String +toString():String PrintDetails():void + Lecturer() + Lecturer(String,String) +setRoomNo():void +getRoomNo(String) +setSubject():void +getSubject(String) +toString():String Coding:- 17
  • 18. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Class Admin public class Admin { public Admin(){ } public String toString(){ return "Class Admin"; } } ------------------------------------------------- Class Lecturer public class Lecturer { String room_no,subject; public Lecturer(){ } public Lecturer(String room_no,String subject){ this.room_no=room_no; this.subject=subject; } public void setRoomNo(String newRoom_No){ this.room_no=newRoom_No; } public String getRoomNo(){ return room_no; } public void setSubject(String newSubject){ this.subject=newSubject; } public String getSubject(){ return subject; } public String toString(){ return "Room No : "+room_no+"nSubject : "+subject; } } Class Staff 18
  • 19. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ public class Staff { public static void PrintDetails(Object o){ if (o instanceof Admin){ System.out.println(((Admin)o).toString()+"n***************************"); } else if (o instanceof Lecturer){ System.out.println(((Lecturer)o).toString() +"n***************************"); } } } ---------------------------------------- Class TestStaff import java.util.*; public class TestStaff { public static void main(String[] args) { Scanner scan=new Scanner(System.in); Staff staff=new Staff(); //Class Admin //Use casting Object admin=new Admin(); System.out.println("***************************"); staff.PrintDetails(admin); //Class Lecturer String room_no,subject; System.out.print("Room No : "); room_no=scan.next(); System.out.print("Subject : "); subject=scan.next(); System.out.println("***************************"); staff.PrintDetails(new Lecturer(room_no,subject)); } } Input:- 19
  • 20. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Output:- Question 4:- 20
  • 21. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ import java.util.*; public class TestQ4 { public static void main(String[] args) { String ans; do { int a; Scanner scan=new Scanner(System.in); System.out.println("Enter 1 for Student and 2 for Staff : "); a=scan.nextInt(); if(a==1){ //Class Person Person person=new Person(); String first,last,add; int zip,phone; System.out.print("First Name :"); first=scan.next(); System.out.print("Last Name : "); last=scan.next(); System.out.print("Address : "); add=scan.next(); System.out.print("Zip Code : "); zip=scan.nextInt(); System.out.print("Phone No : "); phone=scan.nextInt(); person.setFirstName(first); person.setLastName(last); person.setStreetAddress(add); person.setZipCode(zip); person.setPhoneNumber(phone); System.out.println("***************************"+"nClass Person"); System.out.println(person.toString()); System.out.println("***************************"); //Class Student Student student=new Student(); String major,point; System.out.print("Major Field : "); major=scan.next(); System.out.print("Grade Point Average : "); point=scan.next(); student.setMajorField(major); student.setGradePointAverage(point); System.out.println("***************************"+"nClass Student"); System.out.println(student.toString()); System.out.println("***************************"); } else if(a==2) { //Class Employee Employee employee=new Employee(); String office; double salary; int day,year; 21
  • 22. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ String month; System.out.println("Office Name : "); office=scan.next(); System.out.println("Salary : "); salary=scan.nextDouble(); System.out.println("Date Hired (mm/dd/yyyy) : "); System.out.println("Month"); month=scan.next(); System.out.println("Day"); day=scan.nextInt(); System.out.println("Year"); year=scan.nextInt(); MyDate date=new MyDate(year,month,day); date.toString(); employee.setOffice(office); employee.setSalary(salary); employee.setDateHired(date.toString()); System.out.println("**************************"+"nClass Employee"); System.out.println(employee.toString()); System.out.println("***************************"); //Class Faculty Faculty faculty=new Faculty(); int officeHours1,officeHours2; String rank; System.out.println("Office Hours : "); officeHours1=scan.nextInt(); System.out.println("to"); officeHours2=scan.nextInt(); System.out.println("Rank : "); rank=scan.next(); faculty.setOfficeHours1(officeHours1); faculty.setOfficeHours2(officeHours2); faculty.setRank(rank); System.out.println("***************************"+"nClass Faculty"); System.out.println(faculty.toString()); System.out.println("***************************"); //Class Staff Staff staff=new Staff(); String title; System.out.println("Title : "); title=scan.next(); staff.setTitle(title); System.out.println("***************************"+"nClass Staff"); System.out.println(staff.toString()); System.out.println("***************************"); //Print(new Object()); } System.out.println("Do it again (Y/N)?"); ans=scan.next(); } while (ans.equalsIgnoreCase("Y")); } } 22
  • 23. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Input:- Output:- 23
  • 24. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ 24
  • 25. SSK 3101 – LAB 4 Semester 1 2011/2012 ____________________________________________________________________________ Kelebihan polymorphism 1. Code that is more dynamic at runtime 2. Code is more flexible and reusable 3. Code re-usability: Using the code written somewhere in program 4. Multiple forms of one object are called in the same way 25