# Object-Oriented Programming in Java



## JGuru (Dec 3, 2014)

*Object-Oriented Programming in Java*

*Problems with Procedural Langauages*

OOPS was invented because procedural languages such as C, Pascal, BASIC were found to be inadequate for large and complex programs.
One difficulty with this kind of function-based organisation was it focussed on functions at the expense of data. The data could be
local to the function or it could be global. This caused problems when several functions needed to access the same data. To be available 
to more than one function , such variables had to be global, but global data could be accessed inadvertently by any functionin he program.
This lead to frequent program errors!!

*Objects*
Here is the amazing breakthrough that is key to OOP. An object contains functions and variables. A Thermostat object would contain not
only furnaceOn() and furnaceOff() functions, but also currentTemp and desiredTemp. Incidentally in Java , functions are called methods and
variables are called fields.

Ths new entity, the Object solves sveral problems simultaneously. Not only does a Programming object correspond more accurately to objects in the real world, it also
solves the problem engendered by global data in the procedural model.


```
class Thermostat {

    private float currentTemp;
    private float desiredTemp;
    
    public void furnaceOn() {
       // mehod body goes here    
    }
    
    public void furnaceOff() {
           // mehod body goes here    
    }
    
} // End class Thermostat
```

*Object-Oriented Programming Concepts*

What Is an Object?

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.

Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.

Bundling code into individual software objects provides a number of benefits, including:

    Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

    Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

    Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

    Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

What Is a Class?

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

The following Bicycle class is one possible implementation of a bicycle:


```
class Bicycle {

    int cadence = 0;
    int speed = 0;
    int gear = 1;

    void changeCadence(int newValue) {
         cadence = newValue;
    }

    void changeGear(int newValue) {
         gear = newValue;
    }

    void speedUp(int increment) {
         speed = speed + increment;   
    }

    void applyBrakes(int decrement) {
         speed = speed - decrement;
    }

    void printStates() {
         System.out.println("cadence:" +
             cadence + " speed:" + 
             speed + " gear:" + gear);
    }
}
```

The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.

Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:


```
class BicycleDemo {
    public static void main(String[] args) {

        // Create two different 
        // Bicycle objects
        Bicycle bike1 = new Bicycle();
        Bicycle bike2 = new Bicycle();

        // Invoke methods on 
        // those objects
        bike1.changeCadence(50);
        bike1.speedUp(10);
        bike1.changeGear(2);
        bike1.printStates();

        bike2.changeCadence(50);
        bike2.speedUp(10);
        bike2.changeGear(2);
        bike2.changeCadence(40);
        bike2.speedUp(10);
        bike2.changeGear(3);
        bike2.printStates();
    }
}
```

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:

cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3

What Is Inheritance?

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:


```
class MountainBike extends Bicycle {

    // new fields and methods defining 
    // a mountain bike would go here

}
```

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

What Is an Interface?

As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.

In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:


```
interface Bicycle {

    //  wheel revolutions per minute
    void changeCadence(int newValue);

    void changeGear(int newValue);

    void speedUp(int increment);

    void applyBrakes(int decrement);
}
```

To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:


```
class ACMEBicycle implements Bicycle {

    // remainder of this class 
    // implemented as before
}
```

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

What Is a Package?

A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.

The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work.

The Java Platform API Specification contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java SE platform. Load the page in your browser and bookmark it. As a programmer, it will become your single most important piece of reference documentation.

Here are some more code using OOPS.

Course.java


```
// A MODEL class.
 import java.util.*;
public class Course {
    //------------
// Attributes.
//------------
    private String courseNo;
    private String courseName;
    private double credits;
    private Vector offeredAsSection; // of Section object references
    private Vector prerequisites; // of Course object references
//----------------
// Constructor(s).
//----------------

    public Course(String cNo, String cName, double credits) {
        setCourseNo(cNo);
        setCourseName(cName);
        setCredits(credits);
// Note that we must instantiate empty vectors.
        offeredAsSection = new Vector();
        prerequisites = new Vector();
    }
    //-----------------
// Get/set methods.
//-----------------
    public void setCourseNo(String cNo) {
        courseNo = cNo;
    }
    public String getCourseNo() {
        return courseNo;
    }
    public void setCourseName(String cName) {
        courseName = cName;
    }
    public String getCourseName() {
        return courseName;
    }
    public void setCredits(double c) {
        credits = c;
    }
    public double getCredits() {
        return credits;
    }
    //-----------------------------
// Miscellaneous other methods.
//-----------------------------
// Used for testing purposes.
    public void display() {
        System.out.println("Course Information:");
        System.out.println("\tCourse No.: " + getCourseNo());
        System.out.println("\tCourse Name: " + getCourseName());
        System.out.println("\tCredits: " + getCredits());
        System.out.println("\tPrerequisite Courses:");

    }

    public void test() {
        // We take advantage of another of the Course class's
// methods in stepping through all of the prerequisites.
        Enumeration e = getPrerequisites();
        while (e.hasMoreElements()) {
            Course c = (Course) e.nextElement();
            System.out.println("\t\t" + c.toString());
        }
// Note use of print vs. println in next line of code.
        System.out.print("\tOffered As Section(s): ");
        for(int i = 0; i < offeredAsSection.size(); i++) {
            Section s = (Section) offeredAsSection.elementAt(i);
            System.out.print(s.getSectionNo() + " ");
        }
// Print a blank line.
        System.out.println("");

    }

    public String toString() {
        return getCourseNo() + ": " + getCourseName();
    }
    public void addPrerequisite(Course c) {
        prerequisites.add(c);
    }
    public boolean hasPrerequisites() {
        if (prerequisites.size() > 0) return true;
        else return false;
    }
    public Enumeration getPrerequisites() {
        return prerequisites.elements();
    }
    public Section scheduleSection(char day, String time, String room,
                                   int capacity) {
// Create a new Section (note the creative way in
// which we are assigning a section number) ...
        Section s = new Section(offeredAsSection.size() + 1,
                day, time, this, room, capacity);
// ... and then remember it!
        offeredAsSection.addElement(s);
        return s;
    }
}
```

Person.java


```
/**
 * Created with IntelliJ IDEA.
 * User: JGuru
 * Date: 7/23/14
 * Time: 5:16 PM
 * To change this template use File | Settings | File Templates.
 */
// Person.java - Chapter 14 version.
// Copyright 2000 by Jacquie Barker - all rights reserved.
// A MODEL class.
// We are making this class abstract because we do not wish for it
// to be instantiated.
public abstract class Person {
    //------------
// Attributes.
//------------
    private String name;
    private String ssn;
    //----------------
// Constructor(s).
//----------------
    public Person(String name, String ssn) {
        setName(name);
        setSsn(ssn);
    }
    // We're replacing the default constructor that got "wiped out"
// as a result of having created a constructor above.
    public Person() {
        setName("?");
        setSsn("???-??-????");
    }
    //-----------------
// Get/set methods.
//-----------------
    public void setName(String n) {
        name = n;
    }
    public String getName() {
        return name;
    }
    public void setSsn(String ssn) {
        this.ssn = ssn;
    }
    public String getSsn() {
        return ssn;
    }
    //-----------------------------
// Miscellaneous other methods.
//-----------------------------

    // We'll let each subclass determine how it wishes to be
// represented as a String value.
    public abstract String toString();
    // Used for testing purposes.
    public void display() {
        System.out.println("Person Information:");
        System.out.println("\tName: " + getName());
        System.out.println("\tSoc. Security No.: " + getSsn());
    }
}
```

Professor.java


```
/**
 * Created with IntelliJ IDEA.
 * User: JGuru
 * Date: 7/23/14
 * Time: 5:17 PM
 * To change this template use File | Settings | File Templates.
 */

import java.util.*;
public class Professor extends Person {
    //------------
// Attributes.
//------------
    private String title;
    private String department;
    private Vector teaches; // of Sections
    //----------------
// Constructor(s).
//----------------
    public Professor(String name, String ssn, String title, String dept) {
// Reuse the parent constructor with two arguments.
        super(name, ssn);
        setTitle(title);
        setDepartment(dept);
// Note that we must instantiate an empty vector.
        teaches = new Vector();
    }

    //-----------------
// Get/set methods.
//-----------------
    public void setTitle(String title) {
        this.title = title;
    }
    public String getTitle() {
        return title;
    }
    public void setDepartment(String dept) {
        department = dept;
    }
    public String getDepartment() {
        return department;
    }
    //-----------------------------
// Miscellaneous other methods.
//-----------------------------
// Used for testing purposes.
    public void display() {
// First, let's display the generic Person info.
        super.display();
// Then, display Professor-specific info.
        System.out.println("Professor-Specific Information:");
        System.out.println("\tTitle: " + getTitle());
        System.out.println("\tTeaches for Dept.: " + getDepartment());
        displayTeachingAssignments();
    }
    // We are forced to program this method because it is specified
// as an abstract method in our parent class (Person); failing to
// do so would render the Professor class abstract, as well.
//
// For a Professor, we wish to return a String as follows:
//
// Josephine Blow (Associate Professor, Math)
    public String toString() {
        return getName() + " (" + getTitle() + ", " +
                getDepartment() + ")";
    }
    public void displayTeachingAssignments() {
        System.out.println("Teaching Assignments for " + getName() + ":");

// We'll step through the teaches Vector, processing
// Section objects one at a time.
        if (teaches.size() == 0)
            System.out.println("\t(none)");
        else for (int i = 0; i < teaches.size(); i++) {
// Because we are going to need to delegate a lot of the effort
// of satisfying this request to the various Section objects that
// comprise the Professor's teaching load, we "pull" the Section
// object once, and refer to it by a temporarily handle.
            Section s = (Section) teaches.elementAt(i);
// Note how we call upon the Section object to do
// a lot of the work for us!
            System.out.println("\tCourse No.: " +
                    s.getRepresentedCourse().getCourseNo());
            System.out.println("\tSection No.: " +
                    s.getSectionNo());
            System.out.println("\tCourse Name: " +
                    s.getRepresentedCourse().getCourseName());
            System.out.println("\tDay and Time: " +
                    s.getDayOfWeek() + " - " +
                    s.getTimeOfDay());
            System.out.println("\t-----");
        }
    }
    public void agreeToTeach(Section s) {
        teaches.addElement(s);
// We need to link this bidirectionally.
        s.setInstructor(this);
    }
}
```

ScheduleOfClasses.java


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 7/23/14
 * Time: 5:19 PM
 * To change this template use File | Settings | File Templates.
 */
import java.util.*;
public class ScheduleOfClasses {
    //------------
// Attributes.
//------------
    private String semester;
    // This Hashtable stores Section object references, using
// a String concatenation of course no. and section no. as the
// key, e.g., "MATH101 - 1".
    private Hashtable sectionsOffered;
    //----------------
// Constructor(s).
//----------------
    public ScheduleOfClasses(String semester) {
        setSemester(semester);
// Instantiate a new Hashtable.
        sectionsOffered = new Hashtable();
    }
    //-----------------
// Get/set methods.
//-----------------
    public void setSemester(String semester) {
        this.semester = semester;
    }
    public String getSemester() {
        return semester;
    }
    //-----------------------------
// Miscellaneous other methods.
//-----------------------------
// Used for testing purposes.
    public void display() {
        System.out.println("Schedule of Classes for " + getSemester());
        System.out.println("");
// Step through the Hashtable and display all entries.
        Enumeration e = sectionsOffered.elements();
        while (e.hasMoreElements()) {
            Section s = (Section) e.nextElement();
            s.display();
            System.out.println("");
        }
    }

    public void addSection(Section s) {
// We formulate a key by concatenating the course no.
// and section no., separated by a hyphen.
        String key = s.getRepresentedCourse().getCourseNo() +
                " - " + s.getSectionNo();
        sectionsOffered.put(key, s);
// Bidirectionally hook the ScheduleOfClasses back to the Section.
        s.setOfferedIn(this);
    }
}
```

Section.java


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 7/23/14
 * Time: 5:20 PM
 * To change this template use File | Settings | File Templates.
 */
import java.util.*;
public class Section {
    //------------
// Attributes.
//------------
    private int sectionNo;
    private char dayOfWeek;
    private String timeOfDay;
    private String room;
    private int seatingCapacity;
    private Course representedCourse;
    private ScheduleOfClasses offeredIn;
    private Professor instructor;
    // The enrolledStudents Hashtable stores Student object references,
// using each Student's ssn as a String key.
    private Hashtable enrolledStudents;
    // The assignedGrades Hashtable stores TranscriptEntry object
// references, using a reference to the Student to whom it belongs
// as the key.
    private Hashtable assignedGrades;
    // We use PUBLIC STATIC int attributes to declare status codes
// that other classes can then inspect/interpret (see method
// reportStatus() in class SRS.java for an example of how these
// are used).

    public static final int SUCCESSFULLY_ENROLLED = 0;
    public static final int SECTION_FULL = 1;
    public static final int PREREQ_NOT_SATISFIED = 2;
    public static final int PREVIOUSLY_ENROLLED = 3;
    //----------------
// Constructor(s).
//----------------
    public Section(int sNo, char day, String time, Course course,
                   String room, int capacity) {
        setSectionNo(sNo);
        setDayOfWeek(day);
        setTimeOfDay(time);
        setRepresentedCourse(course);
        setRoom(room);
        setSeatingCapacity(capacity);
// A Professor has not yet been identified.
        setInstructor(null);
// Note that we must instantiate empty hash tables.
        enrolledStudents = new Hashtable();
        assignedGrades = new Hashtable();
    }
    //-----------------
// Get/set methods.
//-----------------
    public void setSectionNo(int no) {
        sectionNo = no;
    }
    public int getSectionNo() {
        return sectionNo;
    }
    public void setDayOfWeek(char day) {
        dayOfWeek = day;
    }
    public char getDayOfWeek() {
        return dayOfWeek;
    }
    public void setTimeOfDay(String time) {
        timeOfDay = time;
    }
    public String getTimeOfDay() {
        return timeOfDay;
    }

    public void setInstructor(Professor prof) {
        instructor = prof;
    }
    public Professor getInstructor() {
        return instructor;
    }
    public void setRepresentedCourse(Course c) {
        representedCourse = c;
    }
    public Course getRepresentedCourse() {
        return representedCourse;
    }
    public void setRoom(String r) {
        room = r;
    }
    public String getRoom() {
        return room;
    }
    public void setSeatingCapacity(int c) {
        seatingCapacity = c;
    }
    public int getSeatingCapacity() {
        return seatingCapacity;
    }
    public void setOfferedIn(ScheduleOfClasses soc) {
        offeredIn = soc;
    }
    public ScheduleOfClasses getOfferedIn() {
        return offeredIn;
    }
    //-----------------------------
// Miscellaneous other methods.
//-----------------------------
// For a Section, we want its String representation to look
// as follows:
//
// MATH101 - 1 - M - 8:00 AM
    public String toString() {
        return getRepresentedCourse().getCourseNo() + " - " +
                getSectionNo() + " - " +
                getDayOfWeek() + " - " +
                getTimeOfDay();
    }
    // The full section number is a concatenation of the
// course no. and section no., separated by a hyphen;
// e.g., "ART101 - 1".
    public String getFullSectionNo() {
        return getRepresentedCourse().getCourseNo() +

        " - " + getSectionNo();
    }
    public int enroll(Student s) {
// First, make sure that this Student is not already
// enrolled for this Section, and that he/she has
// NEVER taken and passed the course before.
        Transcript transcript = s.getTranscript();
        if (s.isEnrolledIn(this) ||
                transcript.verifyCompletion(this.getRepresentedCourse()))
            return PREVIOUSLY_ENROLLED;
// If there are any prerequisites for this course,
// check to ensure that the Student has completed them.
        Course c = getRepresentedCourse();
        if (c.hasPrerequisites()) {
            Enumeration e = c.getPrerequisites();
            while (e.hasMoreElements()) {
                Course pre = (Course) e.nextElement();
// See if the Student's Transcript reflects
// successful completion of the prerequisite.
                if (!transcript.verifyCompletion(pre))
                    return PREREQ_NOT_SATISFIED;
            }
        }
// If the total enrollment is already at the
// the capacity for this Section, we reject this
// enrollment request.
        if (!confirmSeatAvailability()) return SECTION_FULL;
// If we made it to here in the code, we're ready to
// officially enroll the Student.
// Note bidirectionality: this Section holds
// onto the Student via the Hashtable, and then
// the Student is given a handle on this Section.
        enrolledStudents.put(s.getSsn(), s);
        s.addSection(this);
        return SUCCESSFULLY_ENROLLED;
    }
    // A private "housekeeping" method.
    private boolean confirmSeatAvailability() {
        if (enrolledStudents.size() < getSeatingCapacity())
            return true;
        else return false;
    }
    public boolean drop(Student s) {
// We may only drop a student if he/she is enrolled.

        if (!s.isEnrolledIn(this)) return false;
        else {
// Find the student in our Hashtable, and remove it.
            enrolledStudents.remove(s.getSsn());
// Note bidirectionality.
            s.dropSection(this);
            return true;
        }
    }
    public int getTotalEnrollment() {
        return enrolledStudents.size();
    }
    // Used for testing purposes.
    public void display() {
        System.out.println("Section Information:");
        System.out.println("\tSemester: " + getOfferedIn().getSemester());
        System.out.println("\tCourse No.: " +
                getRepresentedCourse().getCourseNo());
        System.out.println("\tSection No: " + getSectionNo());
        System.out.println("\tOffered: " + getDayOfWeek() +
                " at " + getTimeOfDay());
        System.out.println("\tIn Room: " + getRoom());
        if (getInstructor() != null)
            System.out.println("\tProfessor: " +
                    getInstructor().getName());
        displayStudentRoster();
    }
    // Used for testing purposes.
    public void displayStudentRoster() {
        System.out.print("\tTotal of " + getTotalEnrollment() +
                " students enrolled");
// How we punctuate the preceding message depends on
// how many students are enrolled (note that we used
// a print() vs. println() call above).
        if (getTotalEnrollment() == 0) System.out.println(".");
        else System.out.println(", as follows:");
// Use an Enumeration object to "walk through" the
// hash table.
        Enumeration e = enrolledStudents.elements();
        while (e.hasMoreElements()) {
            Student s = (Student) e.nextElement();
            System.out.println("\t\t" + s.getName());
        }
    }
    // This method returns the value null if the Student has not
// been assigned a grade.

    public String getGrade(Student s) {
// Retrieve the Student's transcript entry object, if one
// exists, and in turn retrieve its assigned grade.
        TranscriptEntry te = (TranscriptEntry) assignedGrades.get(s);
        if (te != null) {
            String grade = te.getGrade();
            return grade;
        }
// If we found no TranscriptEntry for this Student, return
// a null value to signal this.
        else return null;
    }
    public boolean postGrade(Student s, String grade) {
// Make sure that we haven't previously assigned a
// grade to this Student by looking in the Hashtable
// for an entry using this Student as the key. If
// we discover that a grade has already been assigned,
// we return a value of false to indicate that
// we are at risk of overwriting an existing grade.
// (A different method, eraseGrade(), can then be written
// to allow a Professor to change his/her mind.)
        if (assignedGrades.get(s) != null) return false;
// First, we create a new TranscriptEntry object. Note
// that we are passing in a reference to THIS Section,
// because we want the TranscriptEntry object,
// as an association class ..., to maintain
// "handles" on the Section as well as on the Student.
// (We'll let the TranscriptEntry constructor take care of
// "hooking" this T.E. to the correct Transcript.)
        TranscriptEntry te = new TranscriptEntry(s, grade, this);
// Then, we "remember" this grade because we wish for
// the connection between a T.E. and a Section to be
// bidirectional.
        assignedGrades.put(s, te);
        return true;
    }
    public boolean isSectionOf(Course c) {
        if (c == representedCourse) return true;
        else return false;
    }
}
```

SRS.java


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 7/23/14
 * Time: 5:22 PM
 * To change this template use File | Settings | File Templates.
 */
import java.util.*;
public class SRS {
    // We can effectively create "global" data by declaring
// PUBLIC STATIC attributes in the main class.
// Entry points/"roots" for getting at objects.
    public static ScheduleOfClasses scheduleOfClasses =
            new ScheduleOfClasses("SP2001");
    // Note that we could encapsulate the rest of these, the way that we
// did for the ScheduleOfClasses ...
    public static Vector faculty; // of Professors
    public static Vector studentBody; // of Students
    public static Vector courseCatalog; // of Courses
    public static void main(String[] args) {
        Professor p1, p2, p3;
        Student s1, s2, s3;
        Course c1, c2, c3, c4, c5;
        Section sec1, sec2, sec3, sec4, sec5, sec6, sec7, sec8;
        sec8 = null;
// Create various objects by calling the appropriate
// constructors. (We'd normally be reading in such data
// from a database or file ...)
// -----------
// Professors.
// -----------
        p1 = new Professor("Jacquie Barker", "123-45-6789",
                "Adjunct Professor", "Information Technology");
        p2 = new Professor("John Smith", "567-81-2345",
                "Full Professor", "Chemistry");
        p3 = new Professor("Snidely Whiplash", "987-65-4321",
                "Full Professor", "Physical Education");
// Add these to the appropriate Vector.
        faculty = new Vector();
        faculty.add(p1);
        faculty.add(p2);
        faculty.add(p3);
// ---------
// Students.
// ---------
        s1 = new Student("Joe Blow", "111-11-1111", "Math", "M.S.");
        s2 = new Student("Fred Schnurd", "222-22-2222",
                "Information Technology", "Ph. D.");
        s3 = new Student("Mary Smith", "333-33-3333", "Physics", "B.S.");
// Add these to the appropriate Vector.

        studentBody = new Vector();
        studentBody.add(s1);
        studentBody.add(s2);
        studentBody.add(s3);
// --------
// Courses.
// --------
        c1 = new Course("CMP101",
                "Beginning Computer Technology", 3.0);
        c2 = new Course("OBJ101",
                "Object Methods for Software Development", 3.0);
        c3 = new Course("CMP283",
                "Higher Level Languages (Java)", 3.0);
        c4 = new Course("CMP999",
                "Living Brain Computers", 3.0);
        c5 = new Course("ART101",
                "Beginning Basketweaving", 3.0);
// Add these to the appropriate Vector.
        courseCatalog = new Vector();
        courseCatalog.add(c1);
        courseCatalog.add(c2);
        courseCatalog.add(c3);
        courseCatalog.add(c4);
        courseCatalog.add(c5);
// Establish some prerequisites (c1 => c2 => c3 => c4).
        c2.addPrerequisite(c1);
        c3.addPrerequisite(c2);
        c4.addPrerequisite(c3);
// ---------
// Sections.
// ---------
// Schedule sections of each Course by calling the
// scheduleSection method of Course (which internally
// invokes the Section constructor).
        sec1 = c1.scheduleSection('M', "8:10 - 10:00 PM", "GOVT101", 30);
        sec2 = c1.scheduleSection('W', "6:10 - 8:00 PM", "GOVT202", 30);
        sec3 = c2.scheduleSection('R', "4:10 - 6:00 PM", "GOVT105", 25);
        sec4 = c2.scheduleSection('T', "6:10 - 8:00 PM", "SCI330", 25);
        sec5 = c3.scheduleSection('M', "6:10 - 8:00 PM", "GOVT101", 20);
        sec6 = c4.scheduleSection('R', "4:10 - 6:00 PM", "SCI241", 15);
        sec7 = c5.scheduleSection('M', "4:10 - 6:00 PM", "ARTS25", 40);

// Add these to the Schedule of Classes.
        scheduleOfClasses.addSection(sec1);
        scheduleOfClasses.addSection(sec2);
        scheduleOfClasses.addSection(sec3);
        scheduleOfClasses.addSection(sec4);
        scheduleOfClasses.addSection(sec5);
        scheduleOfClasses.addSection(sec6);
        scheduleOfClasses.addSection(sec7);
// Recruit a professor to teach each of the sections.
        p3.agreeToTeach(sec1);
        p2.agreeToTeach(sec2);
        p1.agreeToTeach(sec3);
        p3.agreeToTeach(sec4);
        p1.agreeToTeach(sec5);
        p2.agreeToTeach(sec6);
        p3.agreeToTeach(sec7);
        System.out.println("Student registration has begun!");
        System.out.println("");
// Students drop/add courses.
        System.out.println("Student " + s1.getName() +
                " is attempting to enroll in " +
                sec1.toString());
        int status = sec1.enroll(s1);
// Note the use of a special method to interpret
// and display the outcome of this enrollment request.
// (We could have included the code in-line here, but
// since (a) it is rather complex and (b) it will need
// to be repeated for all subsequent enrollment requests
// below, it made sense to turn it into a reusable method
// instead.)
        reportStatus(status);
// Try enrolling the same Student in a different Section
// of the SAME Course!
        System.out.println("Student " + s1.getName() +
                " is attempting to enroll in " +
                sec2.toString());
        status = sec2.enroll(s1);
        reportStatus(status);
        System.out.println("Student " + s2.getName() +
                " is attempting to enroll in " +
                sec2.toString());
        status = sec2.enroll(s2);
        reportStatus(status);
        System.out.println("Student " + s2.getName() +
                " is attempting to enroll in " +
                sec3.toString());
        status = sec3.enroll(s2);
        reportStatus(status);

        System.out.println("Student " + s2.getName() +
                " is attempting to enroll in " +
                sec7.toString());
        status = sec7.enroll(s2);
        reportStatus(status);
        System.out.println("Student " + s3.getName() +
                " is attempting to enroll in " +
                sec1.toString());
        status = sec1.enroll(s3);
        reportStatus(status);
        System.out.println("Student " + s3.getName() +
                " is attempting to enroll in " +
                sec5.toString());
        status = sec5.enroll(s3);
        reportStatus(status);
// Skip a line.
        System.out.println("");
// When the dust settles, here's what folks wound up
// being registered for:
//
// sec1: s1, s3
// sec2: s2
// sec7: s2
// Semester is finished (boy, that was quick!). Professors
// assign grades.
        sec1.postGrade(s1, "C+");
        sec1.postGrade(s3, "A");
        sec2.postGrade(s2, "B+");
        sec7.postGrade(s2, "A-");
// Let's see if everything got set up properly
// by calling various display methods!
        System.out.println("====================");
        System.out.println("Schedule of Classes:");
        System.out.println("====================");
        System.out.println("");
        scheduleOfClasses.display();
        System.out.println("======================");
        System.out.println("Professor Information:");
        System.out.println("======================");
        System.out.println("");
        p1.display();
        System.out.println("");
        p2.display();
        System.out.println("");
        p3.display();
        System.out.println("");
        System.out.println("====================");
        System.out.println("Student Information:");
        System.out.println("====================");
        System.out.println("");
        s1.display();

        System.out.println("");
        s2.display();
        System.out.println("");
        s3.display();
    }
    // Note that this is a static method ...
    public static void reportStatus(int status) {
        if (status == Section.SUCCESSFULLY_ENROLLED)
            System.out.println("outcome: SUCCESSFULLY_ENROLLED");
        else if (status == Section.PREREQ_NOT_SATISFIED)
            System.out.println("outcome: PREREQ_NOT_SATISFIED");
        else if (status == Section.PREVIOUSLY_ENROLLED)
            System.out.println("outcome: PREVIOUSLY_ENROLLED");
        else if (status == Section.SECTION_FULL)
            System.out.println("outcome: SECTION_FULL");
    }
}
```


Student.java


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 7/23/14
 * Time: 5:24 PM
 * To change this template use File | Settings | File Templates.
 */
import java.util.*;
public class Student extends Person {
    //------------
// Attributes.
//------------
    private String major;
    private String degree;
    private Transcript transcript;
    private Vector attends; // of Sections
    //----------------
// Constructor(s).
//----------------
    public Student(String name, String ssn, String major, String degree) {
// Reuse the code of the parent's constructor.
        super(name, ssn);
        setMajor(major);
        setDegree(degree);
// Create a brand new Transcript.
        setTranscript(new Transcript(this));
// Note that we must instantiate an empty vector.

        attends = new Vector();
    }
    // A second form of constructor, used when a Student has not yet
// declared a major or degree.
    public Student(String name, String ssn) {
// Reuse the code of the other Student constructor.
        this(name, ssn, "TBD", "TBD");
    }
    //-----------------
// Get/set methods.
//-----------------
    public void setMajor(String major) {
        this.major = major;
    }
    public String getMajor() {
        return major;
    }
    public void setDegree(String degree) {
        this.degree = degree;
    }
    public String getDegree() {
        return degree;
    }
    public void setTranscript(Transcript t) {
        transcript = t;
    }
    public Transcript getTranscript() {
        return transcript;
    }
    //-----------------------------
// Miscellaneous other methods.
//-----------------------------
// Used for testing purposes.
    public void display() {
// First, let's display the generic Person info.
        super.display();
// Then, display Student-specific info.
        System.out.println("Student-Specific Information:");
        System.out.println("\tMajor: " + getMajor());
        System.out.println("\tDegree: " + getDegree());
        displayCourseSchedule();
        printTranscript();
    }

    // We are forced to program this method because it is specified
// as an abstract method in our parent class (Person); failing to
// do so would render the Student class abstract, as well.
//
// For a Student, we wish to return a String as follows:
//
// Joe Blow (123-45-6789) [Master of Science - Math]
    public String toString() {
        return getName() + " (" + getSsn() + ") [" + getDegree() +
                " - " + getMajor() + "]";
    }
    public void displayCourseSchedule() {
// Display a title first.
        System.out.println("Course Schedule for " + getName());
// Step through the Vector of Section objects,
// processing these one by one.
        for (int i = 0; i < attends.size(); i++) {
            Section s = (Section) attends.elementAt(i);
// Since the attends Vector contains Sections that the
// Student took in the past as well as those for which
// the Student is currently enrolled, we only want to
// report on those for which a grade has not yet been
// assigned.
            if (s.getGrade(this) == null) {
                System.out.println("\tCourse No.: " +
                        s.getRepresentedCourse().getCourseNo());
                System.out.println("\tSection No.: " +
                        s.getSectionNo());
                System.out.println("\tCourse Name: " +
                        s.getRepresentedCourse().getCourseName());
                System.out.println("\tMeeting Day and Time Held: " +
                        s.getDayOfWeek() + " - " +
                        s.getTimeOfDay());
                System.out.println("\tRoom Location: " +
                        s.getRoom());
                System.out.println("\tProfessor's Name: " +
                        s.getInstructor().getName());
                System.out.println("\t-----");
            }
        }
    }
    public void addSection(Section s) {
        attends.addElement(s);
    }
    public void dropSection(Section s) {
        attends.remove(s);
    }
    // Determine whether the Student is already enrolled in THIS
// EXACT Section.

    public boolean isEnrolledIn(Section s) {
        if (attends.contains(s)) return true;
        else return false;
    }
    public void printTranscript() {
        getTranscript().display();
    }
    // Determine whether the Student is already enrolled in ANOTHER
// Section of this SAME Course.
    public boolean isCurrentlyEnrolledInSimilar(Section s1) {
        boolean foundMatch = false;
        Course c1 = s1.getRepresentedCourse();
        Enumeration e = getEnrolledSections();
        while (e.hasMoreElements()) {
            Section s2 = (Section) e.nextElement();
            Course c2 = s2.getRepresentedCourse();
            if (c1 == c2) {
// There is indeed a Section in the attends()
// Vector representing the same Course.
// Check to see if the Student is CURRENTLY
// ENROLLED (i.e., whether or not he has
// yet received a grade). If there is no
// grade, he/she is currently enrolled; if
// there is a grade, then he/she completed
// the course some time in the past.
                if (s2.getGrade(this) == null) {
// No grade was assigned! This means
// that the Student is currently
// enrolled in a Section of this
// same Course.
                    foundMatch = true;
                    break;
                }
            }
        }
        return foundMatch;
    }
    public Enumeration getEnrolledSections() {
        return attends.elements();
    }
}
```

Transcript.java


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 7/23/14
 * Time: 5:25 PM
 * To change this template use File | Settings | File Templates.
 */
import java.util.*;
public class Transcript {
    //------------.
// Attributes.
//------------

    private Vector transcriptEntries; // of TranscriptEntry object references
    private Student studentOwner;
    //----------------
// Constructor(s).
//----------------
    public Transcript(Student s) {
        setStudentOwner(s);
// Need to instantiate a new Vector.
        transcriptEntries = new Vector();
    }
    //-----------------
// Get/set methods.
//-----------------
    public void setStudentOwner(Student s) {
        studentOwner = s;
    }
    public Student getStudentOwner() {
        return studentOwner;
    }
    //-----------------------------
// Miscellaneous other methods.
//-----------------------------
    public boolean verifyCompletion(Course c) {
        boolean outcome = false;
// Step through all TranscriptEntries, looking for one
// which reflects a Section of the Course of interest.
        for (int i = 0; i < transcriptEntries.size(); i++) {
            TranscriptEntry te = (TranscriptEntry)
                    transcriptEntries.elementAt(i);
            Section s = te.getSection();
            if (s.isSectionOf(c)) {
// Ensure that the grade was high enough.
                if (TranscriptEntry.passingGrade(te.getGrade())) {
                    outcome = true;
// We've found one, so we can afford to
// terminate the loop now.
                    break;
                }
            }
        }

        return outcome;
    }
    public void addTranscriptEntry(TranscriptEntry te) {
        transcriptEntries.add(te);
    }
    // Used for testing purposes.
    public void display() {
        System.out.println("Transcript for: " +
                getStudentOwner().toString());
        if (transcriptEntries.size() == 0)
            System.out.println("\t(no entries)");
        else for (int i = 0; i < transcriptEntries.size(); i++) {
            TranscriptEntry te = (TranscriptEntry)
                    transcriptEntries.elementAt(i);
            Section sec = te.getSection();
            Course c = sec.getRepresentedCourse();
            ScheduleOfClasses soc = sec.getOfferedIn();
            System.out.println("\tSemester: " +
                    soc.getSemester());
            System.out.println("\tCourse No.: " +
                    c.getCourseNo());
            System.out.println("\tCredits: " +
                    c.getCredits());
            System.out.println("\tGrade Received: " +
                    te.getGrade());
            System.out.println("\t-----");
        }
    }
}
```

TranscriptEntry.java


```
/**
 * Created with IntelliJ IDEA.
 * User: Sowndar
 * Date: 7/23/14
 * Time: 5:26 PM
 * To change this template use File | Settings | File Templates.
 */
public class TranscriptEntry {
    //------------
// Attributes.
//------------
    private String grade;
    private Student student;
    private Section section;
    private Transcript transcript;
    //----------------
// Constructor(s).
//----------------

    public TranscriptEntry(Student s, String grade, Section se) {
        setStudent(s);
        setSection(se);
        setGrade(grade);
// Obtain the Student's transcript ...
        Transcript t = s.getTranscript();
// ... and then hook the Transcript and the TranscriptEntry
// together bidirectionally.
        setTranscript(t);
        t.addTranscriptEntry(this);
    }
    //-----------------
// Get/set methods.
//-----------------
    public void setStudent(Student s) {
        student = s;
    }
    public Student getStudent() {
        return student;
    }
    public void setSection(Section s) {
        section = s;
    }
    public Section getSection() {
        return section;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    public String getGrade() {
        return grade;
    }
    public void setTranscript(Transcript t) {
        transcript = t;
    }
    public Transcript getTranscript() {
        return transcript;
    }
    //-----------------------------
// Miscellaneous other methods.
//-----------------------------
// These next two methods are declared to be static, so that they
// may be used as utility methods.
    public static boolean validateGrade(String grade) {
        boolean outcome = false;

        if (grade.equals("F") ||
                grade.equals("I")) outcome = true;
        if (grade.startsWith("A") ||
                grade.startsWith("B") ||
                grade.startsWith("C") ||
                grade.startsWith("D")) {
            if (grade.length() == 1) outcome = true;
            else if (grade.length() > 2) outcome = false;
            else {
                if (grade.endsWith("+") ||
                        grade.endsWith("-")) outcome = true;
                else outcome = false;
            }
        }
        return outcome;
    }
    public static boolean passingGrade(String grade) {
// First, make sure it is a valid grade.
        if (!validateGrade(grade)) return false;
// Next, make sure that the grade is a D or better.
        if (grade.startsWith("A") ||
                grade.startsWith("B") ||
                grade.startsWith("C") ||
                grade.startsWith("D")) return true;
        else return false;
    }
}
```


Here are the books you can study to understand OOPS & apply it !!

*Books:*

1) Object-oriented Programming in C++ by Robert Lafore (Waite Group, 1995)

2) Object-Oriented Design Heuristics by Arthur J Riel (Addison Wesley)

3) An Introduction to Object-Oriented Programming by Timothy Budd (Addison Wesley 1996)

4) Object-Oriented Design in Java by Stephen Gilbert and Bill McCarty 

5) Beginning Java Objects (Wrox)

6) Big Java Late Objects by Cay S. Horstmann 

7) Object-Oriented Programming in Java by Stephen Gilbert and Bill McCarty

8) Object-oriented Analysis and Design with Applications by Grady Booch (Addison Wesley , 1994)

9) The Object Primer : The Application Developer's Guide to Object-Orientation by Scott W Ambler

10) Design Patterns : Elements of Reusable Object-Oriented Software by Erich Gamma et al (Addison Wesley)

11) Object-Oriented Programming in Java by Balagurusamy

12) C++ with OOPS by Balagurusamy

These books are available from the best book shops in your city or can can also order it from Online Shopping: Shop Online for Mobiles, Laptops, Cameras, Books, Watches, Apparel, Shoes and More - Amazon.in


----------



## jeniscott (Jun 13, 2015)

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming. Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.


----------



## anirbandd (Jun 13, 2015)

uhh.. good thread.


----------

