8-Sep-03
Air Force Institute of TechnologyElectrical and Computer Engineering
Object-Oriented Programming Design
Topic : Objects and Classes
Maj Joel [email protected]
Maj Joel Young
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 2
Object-Oriented Programming
DesignObject-Oriented Programming Principles
• Organize program into a set of objects with certain properties and operations that the objects perform.
• State of objects may change over time, but you can depend on objects not interacting with each other in an undocumented way
• Objects communicate with other objects via messages which call methods defined in the public interface of the other object -- i.e. clients send messages to server objects which then perform a task for the client object.
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 3
Object-Oriented Programming
DesignCharacteristics of an Object
• State– The internal attributes of a thing, and their values
• Behavior– Operations that affect the state of a thing– Operations a thing performs based on its state– Methods describe how objects behave and how objects from other classes
can interact with an object– Mutator methods change state of object -- setAttribute– Accessor methods return state of object -- getAttribute
• Identity– Given any two things, we can tell them apart from each other– Implementation: Record ID, SS#, memory address, etc.
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 4
Object-Oriented Programming
DesignObject
• Real-world Example– Cruise Control
– User Interface– On/Off– Set– Increase– Decrease
– Implementation– State
– Desired speed– Actual speed
– Operations– Activate– Deactivate– Accelerate– Decelerate
– Identity– Unique instance for each vehicle
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 5
Object-Oriented Programming
DesignObject-Oriented Programming Principles
• Class– Template from which an object is actually made– Specifies operations and states for a type of object– An object that conforms to a class description is an instance of that class– There may be multiple instances (objects) created from a class– Classes themselves are not “objects”
– It’s the difference between saying– “Colleges offer courses” and “AFIT offers CSCE694”
– One is a general statement true for all colleges; the other is a specific example
– Classes describe the general case,– Objects are the specific instances
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 6
Object-Oriented Programming
DesignObject-Oriented Programming Principles
• Encapsulation (aka data hiding)– Hiding implementation of data from user of object– Data in object are instance variables– Functions and procedures in Java class are methods– Encapsulation implemented by preventing other classes from accessing
instance variables in a class except through the class methods
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 7
Object-Oriented Programming
DesignClass Relationships
• Association (uses)– A class uses another class if it manipulates objects of that class
– Method of class A sends message to an object of class B– Method of A creates, receives, or returns objects of class B
• Aggregation (has-a)– Objects of class A contain objects of class B– Special case of use
• Inheritance (is-a) (more on this later)– If class A extends class B, class A inherits methods from class B– Class A is a specialization of class B
Tire
Aut omobi le
1
4
has1
4
Em ployee
is-a
Manager
GasStation
*
*Automobile
uses
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 8
Object-Oriented Programming
DesignClass Relationships
Course-name: String-credits: int+printRoster()+enroll(newStudent: Student)
Student-name: String-studentID: long+printSchedule()
Professor-name: String-title: String+printCourseLoad()
teachesattends
1..*
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 9
Object-Oriented Programming
DesignJava Classes
• A Java class contains:– Attributes (variable declarations, a.k.a. “fields”) – Operations (a.k.a. “methods”)
• General Rules:– A class is given a name using normal identifier rules– Generally only one class per file
– The file must be named the same as the class– File/Class names are case sensitive
• At least one class in an application must contain a “main” method– Starting point for program execution– Legal to have several classes with a “main” method
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 10
Object-Oriented Programming
DesignJava Classes
class Person{
// Attributesprivate String m_name;private int m_age;
// OperationsPerson(String name, int age){
m_name = name;m_age = age;
}public void printPerson(){
System.out.print(“Name:”);System.out.print(m_name);System.out.print(“ Age:”);System.out.println(m_age);
}public int getAge(){
return m_age;}
}
Person
name: Stringage: integer
printPerson()getAge()
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 11
Object-Oriented Programming
DesignAttributes
• Attributes
• Java’s primitive data types – Integer types– Reals
• References to class instances– Java-supplied types (e.g. String)– User-defined types (e.g. Aircraft, Car)
• Inner classes (not discussed in this course)
• Can be initialized in the declaration
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 12
Object-Oriented Programming
DesignJava Classes – Attributes
class ExampleClass
{
// Valid class attributes (default initialization)
private short m_attackFlag; // Defaults to 0
private float Burst_Rate; // Defaults to 0.0
private boolean moving; // Defaults to false
// Valid class attributes
private int m_age = 30;
private double $gpa = 1.7;
private boolean meetsStandard2167a = false;
private char m_initial = ‘c’;
String m_name = “Mathias”;
Aircraft m_acRef = new Aircraft(“F-117”,”Stinkbug”);
}
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 13
Object-Oriented Programming
DesignMethods
• Elements of an operation (“method”) declaration:– Visibility: public, protected, private (default: private)– Return type:
– Any valid primitive type– Class type– void
– Class method declaration (static)– Name
– Same rules as naming a variable– Parameters
– All parameters are passed by value– Yes, that includes references (they just pass a pointer)
– Body
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 14
Object-Oriented Programming
DesignMethods
Basic format: <visibility><type><name>(<params>){
<body>}
class Employee{
public Employee(String n, double s){
_name = n;_salary = s;
}public double salary(){
return _salary;}public void raiseSalary(double percent){
_salary *= 1 + percent/100;}private String _name;private double _salary;
}
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 15
Object-Oriented Programming
DesignMethods
• All parameters are passed by value– must use objects to pass by reference
class Employee{ …
public void swapSalary(Employee b){ double temp = _salary;
_salary = b.salaryb._salary = temp;
}}
– cannot change the value passed as b, but can change the contents– Wrong:
class Employee{ …
public void assign(Employee b, Employee a){
b = a;}
}
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 16
Object-Oriented Programming
DesignScope/Visibility
• Java classes limit the visibility of operations/attributes– public: Anyone can access– private: Only methods in this class can access– protected: Methods in this class+child classes can access
private
protected
public
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 17
Object-Oriented Programming
DesignUsing Class Instances (objects)
• Creating an object– Use the keyword new followed by a constructor
Employee newGuy = new Employee( “Tim”, 1000 );
– Constructors– Default constructor used if none supplied by user– User-defined constructors may be supplied
– Objects created using new are called “references”
• References– Essentially a pointer without the C/C++ notation– No explicit memory deallocation is required– When used as function parameters, copies memory addresses … not the
objects (like C/C++)
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 18
Object-Oriented Programming
DesignUsing Class Instances
• Accessing an instance method:newGuy.raiseSalary( 10.0 );
• Accessing an instance attribute:double hisSalary = newGuy._salary;newSalary = this._salary * ( 1 + percent/100);
//”this” refers to current instance
• Note: direct access to other object’s attributes is discouraged– (and in fact it is not allowed in above case due to private attribute)
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 19
Object-Oriented Programming
DesignConstructors
• Automatically called when object is created• Same name as class -- e.g. Date();• No return value• May be more than one constructor per class• Default constructor with no arguments should be specified
– initialize to reasonable default valuepublic Date(){
_day = 1;_month = 1;_year = 1;
}
• Constructor with arguments -- initialize to user specified valuespublic Date( int d, int m, int y){
_day = d;_month = m;_year = y;
}
• Cannot be invoked on existing objects
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 20
Object-Oriented Programming
DesignConstructors
• A quick quiz on constructors– can you spot the error?
class Employee
{
public Employee( String n, double s ){
String _name = n;double _salary = s;
}…
private String _name;
private double _salary;}
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 21
Object-Oriented Programming
DesignJava Example
class Person{
// Attributesint m_age;double m_gpa;String m_name;
// Operationspublic Person(String name,
int age, double gpa){
m_age = age;m_name = name; m_gpa = gpa;
}
private void printName(){
System.out.print(m_name);}
static public void main(String args[])
{// Create a Person instancePerson p1 =
new Person("Pyle",27,1.9);Person p2;
// Print the name of // the personSystem.out.print("Name: ");p1.printName();p2 = p1;
// Print the same name againSystem.out.print(" Name: ");p2.printName();
}
} // End class Person
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 22
Object-Oriented Programming
DesignClass Attributes/Methods
• Class methods/attributes– Use static keyword in front of declaration
Class MyMath{ …
static void add( int val1, int val2 );
}
– May be accessed by using ClassName.method() or ClassName.attribute notationMyMath.add( 1, 3 );
– An instance of the class is not required for access• Class-wide Attributes
– An attribute shared by all instances of a class– If one instance changes it … all others see the change– Analog: Global Variable … use SPARINGLY
• Class-wide Operation– A “meta operation” … operates on the class, not instances of the class– Typical application:
– Creating new class members, assigning class ID numbers, etc.
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 23
Object-Oriented Programming
DesignPackages
• Java code is distributed in separate packages (you can also create your own packages)
• To access code in a package– refer to class by full name
java.util.Vector v = new java.util.Vector();
– or import class into your programimport java.util.Vector
Vector v = new Vector();
– or import entire packageimport java.util.*
• Package paths map to directory structurejava.util.Vector ⇒
<CLASSPATH>\java\util\<vector package files>
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 24
Object-Oriented Programming
DesignDevelopment Process
• Analysis– Transform vague understanding of a problem into a precise description of
the tasks to be solved– Concerned with description of what must be done, not how it should be
done• Design
– Structure programming tasks into classes and packages (logically grouped clusters of objects)
– Specify operations and attributes of each class– Specify relationships with other classes in the system
• Implementation– Classes and operations are coded, tested, and integrated– Object-orientation encourages evolutionary development since behavior
and state is encapsulated into objects with predefined interfaces – thus objects or packages can be incrementally added and tested more easily
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 25
Object-Oriented Programming
DesignObject-Oriented Design
• Goal: decompose a programming task into data types or class and define the functionality of these classes
• Sub-goals– Identify classes– Identify functionality of classes– Identify relationships among classes
• A good design greatly reduces time required for implementation and testing
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 26
Object-Oriented Programming
DesignObject-Oriented Design
• Finding classes– Look for nouns in problem analysis– Many are good choices for classes– Other classes may be necessary
• Finding operations– Look for verbs in problem analysis– Each operation must have exactly one class responsible for carrying it out
• Finding class relationships– Association uses; a class uses another class if manipulates objects of
that class in any way; should be minimized– Aggregation “has-a”, contains; – Inheritance “is-a”, specialization; useful in select places
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 27
Object-Oriented Programming
DesignObject-Oriented vs. Traditional Design
Traditional
• Decomposition into sub-tasks– Often results in numerous
procedures or functions– Difficult to manage and
understand• Task modules can simulate
objects by organizing related tasks and attributes– Only one instance (e.g. queue)
• Encapsulation achieved with opaque types (e.g. Unix file interface)– No inheritance
Object-Oriented
• Decomposition into objects with associated tasks– Convenient clustering– Data encapsulation helps
debugging– Multiple instances with similar
behavior– Inheritance captures
commonalities among related classes of objects
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 28
Object-Oriented Programming
DesignDesign Hints
• Always keep data private– If user of the class has a need to both read and change a field (attribute),
the following 3 items must be implemented in the class– A private data field– A public field accessor method– A public field mutator method
– Benefits– Internal implementation can be changed without affecting any code
outside of the class– Mutator methods can perform error-checking to ensure field is set
properly– Accessors to fields with mutable objects
– Should return clone of object so that calling object can not modify the field object contained in the class instance
• Always initialize data – Avoids unexpected results– Simplifies debugging
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 29
Object-Oriented Programming
DesignDesign Hints
• Don't use too many basic types in a class– Group related types into a separate class and use that class instead– Bad
class Employee{
– private String _lname;– private String _fname;
– private char _initial;– private String _street;– private String _city;– private String _state;– private long _zip;
}
• Not all fields need individual field accessors and mutators• Use a standard format for class definitions• Break up classes with too many responsibilities• Make the names of your classes and methods reflect their responsibilities
– Goodclass Employee{private Name _name;private Address _address;private Date _hiredate;
}
Air Force Institute of TechnologyElectrical and Computer Engineering8-Sep-03 30
Object-Oriented Programming
DesignHomework
• Compile and run the Person example code• Analyze the requirements for a Calculator program
– Identify the classes, the operations, and the relationships between classes
– Make stub code for all your classes and operations with definitionsfor the has-a relationships
– Remember each class goes in a separate file• Write and test a swap method
– Create a simple class with one int data member– Write a swap method for that class that swaps values:
– : static public void swap(mytype a, mytype b);– Such that after swap(a,b) is called a looks like b looked and b looks
like a looked