slide2.1_2009_r1 - Module 2.1 Module Objects and Classes...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Module 2.1 Module Objects and Classes Objects EE3206/EE5805 Java Programming & Applications EE3206/EE5805 1 Intended Learning Outcomes To understand objects and classes and use classes to model objects. To declare a class and create an object of a class. To understand the roles of constructors. To declare private data fields with appropriate get and set methods to make class easy to maintain. To develop methods with object arguments. To know the difference between instance and static variables and methods. To determine the scope of variables in the context of a class. To use the keyword this as the reference to the current object that invokes the instance method. To store and process objects in arrays. To apply class abstraction to develop software. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 2 Raise of OOP Object-oriented programming (OOP) has roots that can be Object oriented traced to the 1960s. As hardware and software became increasingly complex, quality was often compromised. Researchers studied ways to maintain software quality and developed object-oriented programming in part to address developed oriented common problems by strongly emphasizing discrete, reusable units of programming logic. reusable OOP involves programming using objects. An object represents an entity in the real world that can be distinctly identified. • For example, a student, a car, a circle, a button, and even a loan can all be viewed as objects. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 3 Programming Paradigms OOP Consider data and function as a Consider whole (i.e. object) whole Program is composed of selfProgram sufficient modules that each sufficient contains all the information contain all needed to manipulate its own data structure Program is viewed as a collection of cooperating objects Procedural Programming Consider data and function onsider function separately Program is composed of modules Program that each is responsible for certain functional aspects of the program Program is seen as a list of tasks to perform EE3206/EE5805 Java Programming & Applications EE3206/EE5805 4 Object In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects and can be viewed as an independent 'machine' with a distinct role or responsibility. Modeling with objects is easier as it is an intuitive mapping of Modeling your observation in the real world. your Dealer Player A Player B Cards Chips EE3206/EE5805 Java Programming & Applications EE3206/EE5805 5 Class and Objects Class is a model for building objects Class new EE3206/EE5805 Java Programming & Applications EE3206/EE5805 6 Object An object has a unique identity, state, and behaviors. • The identity is the name of an object. e.g. student // object name • The state of an object consists of a set of data fields (also known as properties) with their current values. e.g. student.age e.g. student.grow() // data field // increase age by 1 • The behavior of an object is defined by a set of methods. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 7 Building Objects Class Name: Circle Data Fields: radius is _______ Methods: getArea A class template Circle Object 1 Data Fields: radius is 10 Methods: getArea Circle Object 2 Data Fields: radius is 25 Methods: getArea Circle Object 3 Data Fields: radius is 125 Methods: getArea Three objects of the Circle class A class specifies how to create an object and tells what the object possesses. The three objects have different states (different values of radius), but have the same behavior (method getArea) as defined by the class which is the blueprint of an object. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 8 Class Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class. class Circle { /** The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * 3.14159; } } EE3206/EE5805 Java Programming & Applications EE3206/EE5805 9 Data field Constructors Method Constructors Circle() { // no-arg constructor // initialize data fields with default values } Circle(double newRadius) { radius = newRadius; } Constructors are a special kind of methods that are invoked to construct objects. Constructors must have the same name as the class itself. Constructors do not have a return type — not even void. No-arg constructor • A constructor with no parameters EE3206/EE5805 Java Programming & Applications EE3206/EE5805 10 Using Constructors • Constructors cannot be invoked as a normal method. They are invoked using the new operator when an object is created. new ClassName(); • Constructors play the role of initializing objects. You should place your code of initialization inside a constructor. new Circle(); new Circle(5.0); // without args // with args EE3206/EE5805 Java Programming & Applications EE3206/EE5805 11 Default Constructor A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. • Automatically inserted by compiler This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 12 Declaring Objects Similar to declaring a variable of primitive data types, you can declare a reference variable for an object, using the syntax: ClassName objectRefVar; Example: Circle myCircle; To reference an object, assign the object to a reference variable. ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); If a reference type variable does not reference any object, the data field holds a special literal value, null. Circle myCircle; // declaration only, implicitly null EE3206/EE5805 Java Programming & Applications EE3206/EE5805 13 Accessing Objects Referencing the object’s data: objectRefVar.data Example: double myRadius = myCircle.radius; Invoking the object’s method: objectRefVar.methodName(arguments) Example: myCircle.getArea(); Objective: • Demonstrate creating objects, accessing data, and using methods. TestCircle1 Run EE3206/EE5805 Java Programming & Applications EE3206/EE5805 14 UML Class Diagram UML Class Diagram Circle radius: double Circle() Circle(newRadius: double) getArea(): double Class name Data fields Constructors and Methods circle1: Circle radius: 10 circle2: Circle radius: 25 circle3: Circle radius: 125 UML notation for objects •Unified Modeling Language (UML) is a standardized specification language for object modeling. •It is a general-purpose modeling language that includes a graphical notation used to create an abstract model of a system, referred to as a UML model. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 15 animation Initializing Objects Declare myCircle Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle null EE3206/EE5805 Java Programming & Applications EE3206/EE5805 16 animation Initializing Objects Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; null myCircle : Circle radius: 5.0 Create a circle EE3206/EE5805 Java Programming & Applications EE3206/EE5805 17 animation Initializing Objects Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; Assign object reference to myCircle reference value myCircle : Circle radius: 5.0 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 18 animation Initializing Objects Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value : Circle radius: 5.0 yourCircle null Declare yourCircle EE3206/EE5805 Java Programming & Applications EE3206/EE5805 19 animation Initializing Objects Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value : Circle radius: 5.0 yourCircle null : Circle Create a new Circle object radius: 1.0 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 20 animation Initializing Objects Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value : Circle radius: 5.0 yourCircle reference value Assign object reference to yourCircle : Circle radius: 1.0 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 21 animation Initializing Objects Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value : Circle radius: 5.0 yourCircle reference value : Circle Change radius in yourCircle radius: 100.0 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 22 Data Fields The data fields can be of primitive types or reference types. Previously, we have mention that String is a reference types. For example, the following Student class contains mixed types of data field. public class Student { String name; String int age; age; boolean isScienceMajor; char gender; char } // // // // // // // name has default value null age has default value 0 isScienceMajor has default value false isScienceMajor c has default value '\u0000' EE3206/EE5805 Java Programming & Applications EE3206/EE5805 23 Default Value for a Data Field All data fields have a default value. • • • • reference type = null numeric type = 0 boolean type = false char type = '\u0000' public class Test { public static void main(String args) { public main(String args Student student = new Student(); Student student System.out.println("name? " + student.name); student.name); System.out.println("age? " + student.age); System.out.println("age student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("isScienceMajor student.isScienceMajor); System.out.println("gender? " + student.gender); System.out.println("gender student.gender); } } EE3206/EE5805 Java Programming & Applications EE3206/EE5805 24 No Default Value for Local Variables However, Java assigns no default value to local variables inside method. public class Test { public static void main(String args) { public args int x; // x has no default value x; // String y; // y has no default value String // System.out.println("x is " + x); is System.out.println("y is " + y); System.out.println("y is } } Compilation error: variables not initialized EE3206/EE5805 Java Programming & Applications EE3206/EE5805 25 Difference between Primitive Type and Object Type C reated u sin g n ew C ircle() P rim itive typ e O b ject typ e int i = 1 C ircle c i c 1 Heap r eference Call Stack c : C ircle r ad ius = 1 Primitive type assignment i = j Before: i j 1 2 After: i j 2 2 Before: c1 c2 Object type assignment c1 = c2 c1 is not being referenced now, and regarded as garbage After: c1 c2 c1: Circle radius = 5 c2: Circle radius = 9 c1: Circle radius = 5 c2: Circle radius = 9 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 26 Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. • Garbage is automatically collected by JVM. • You don’t need to acquire/release memory by yourself. TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 27 Static & Non-static Context Static • • • • • The static context available when the corresponding class loaded into JVM. Variables and methods are associated with classes. Static variables are shared by all the instances of the same class. To declare static variables, constants, and methods, use the static modifier. You access static variables/methods through a class reference. Non-static • • • • The non-static context available when the corresponding class instantiated. (i.e. an object is created) Each object has its own context. Variables and methods are associated with a particular instance. You access instance variables/methods through an object reference. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 28 Static & Non-static Context instantiate circle1 radius = 1 numberOfObjects = 2 Memory 1 radius Circle radius: double numberOfObjects: int 2 getNumberOfObjects(): int getArea(): double instantiate circle2 radius = 5 numberOfObjects = 2 5 numberOfObjects radius UML Notation: underline: static variables or methods Each object has it’s own radius (instance variable), but both circle1 and circle2 share the same numberOfObjects (class variable). EE3206/EE5805 Java Programming & Applications EE3206/EE5805 29 Example of Using Instance and Class Example Variables and Method Variables Objective: • Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberOfObjects to track the number of Circle objects created. TestCircle2 Run EE3206/EE5805 Java Programming & Applications EE3206/EE5805 30 Visibility Modifiers Package level (no visibility modifier) • By default, the class, variable or method can be accessed by any class in the same package. Public level (modifier: public) • No restriction of access • The class, variable or method is visible to any class in any package. Private level (modifier: private) • The variable or method can be accessed only by the declaring class itself. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 31 Restricting Accessibility Restricting Ex 1 Ex package p1; public class C1 { public int x; int y; private int z; public void m1() { can access x, y, z } void m2() { can access x, y, z } private void m3() { can access x, y, z } } public class C2 { void aMethod() { C1 o = new C1(); can access o.x; can access o.y; cannot access o.z; can invoke o.m1(); can invoke o.m2(); cannot invoke o.m3(); } } } } package p2; public class C3 { void aMethod() { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; can invoke o.m1(); cannot invoke o.m2(); cannot invoke o.m3(); Ex 2 Ex package p1; class C1 { ... } public class C2 { can access C1 } package p2; public class C3 { cannot access C1; can access C2; } 32 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 Data Encapsulation Data encapsulation means tying data fields and methods together. Data fields should generally be private such that • • Data are being protected Maintenance of a class is easier We can then allow controlled access through public methods of the same class. These methods are called getter and setter (aka accessor and mutator). They are used to read and modify private properties. TestCircle3 Circle The - sign indicates private modifier -radius: double -numberOfObjects: int +Circle() +Circle(radius: double) The + sign indicates public modifier +getRadius(): double +setRadius(radius: double): void +getNumberOfObject(): int +getArea(): double The radius of this circle (default: 1.0). The number of circle objects created. Constructs a default circle object. Constructs a circle object with the specified radius. Returns the radius of this circle. Sets a new radius for this circle. Returns the number of circle objects created. Returns the area of this circle. 33 EE3206/EE5805 Java Programming & Applications EE3206/EE5805 Class Abstraction Similar to method abstraction, class abstraction means to separate class implementation from the use of the class. • The creator of the class provides a description of the class and let the user know how the class can be used. • The user of the class does not need to know how the class is implemented. The detail of implementation is hidden from the user. Class implementation is like a black box hidden from the clients Class Class Contract (Signatures of public methods and public constants) Clients use the class through the contract of the class EE3206/EE5805 Java Programming & Applications EE3206/EE5805 34 Immutable Objects and Classes If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. If you delete the set method in the Circle3 class in the preceding example, the class would be immutable because radius is private and cannot be changed without a set method. However, a class with all private data fields and without mutators is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is still mutable. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 35 Why Student Mutable? public class Student { private int id; private int private BirthDate birthDate; private BirthDate public Student(int ssn, public Student(int int year, int month, int day) { int year, int month, int id = ssn; id ssn birthDate = new BirthDate(year, month, day); new BirthDate(year } public int getId() { public int return id; } public BirthDate getBirthDate() { public BirthDate return birthDate; return birthDate } } public class BirthDate { public BirthDate private int year; private int private int month; private int private int day; private int public BirthDate(int newYear, public BirthDate(int int newMonth, int newDay) { int int year = newYear; year newYear month = newMonth; month newMonth day = newDay; day newDay } public void setYear(int newYear) { public setYear(int year = newYear; year newYear } } public class Test { public static void main(String args) { public args Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date student.getBirthDate date.setYear(2010); // Now the student birth year is changed! } } EE3206/EE5805 Java Programming & Applications EE3206/EE5805 36 What make Class Immutable? For 1. 2. 3. a class to be immutable, it must mark all data fields private, provide no mutator methods, and provide no accessor methods that would return a reference to a mutable data field object. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 37 Passing Objects to Methods Object is passed by reference. • No additional objects are created. Stack Space required for the printAreas method int times: 5 Circle c: reference Space required for the main method int n: 5 myCircle: reference Pass by value (here the value is 5) Pass the reference of the object Heap A circle object TestPassObject Run EE3206/EE5805 Java Programming & Applications EE3206/EE5805 38 Scope of Variables in Class Data fields • The scope of data fields is the entire class. They can be declared anywhere inside a class, though this is not preferred (lower readability). • They are implicitly initialized with default value. Local variables • The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. • A local variable must be initialized explicitly before it can be used. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 39 The this Keyword The this The keyword this is a reference to the object currently executing. Two common usages: • • To refer to an instance data field. To invoke an overloaded constructor of the same class. public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } this must be explicitly used to reference the data field radius of the object being constructed public Circle() { this(1.0); } this is used to invoke another constructor public double getArea() { return this.radius * this.radius * Math.PI; } } Every instance variable belongs to an instance represented by this, which is normally omitted EE3206/EE5805 Java Programming & Applications EE3206/EE5805 40 Array of Objects Circle circleArray = new Circle[10]; Circle circleArray An array of objects is actually an array of reference variables. Invoking circleArray[1].getArea() involves two levels of referencing as shown in the figure. circleArray references to the entire array. circleArray[1] references to a Circle object. circleArray reference circleArray[0] circleArray[1] … Circle object 0 Circle object 1 Circle object 9 circleArray[9] EE3206/EE5805 Java Programming & Applications EE3206/EE5805 41 Array of Objects This program summarize the areas of ten randomly generated circles. randomly Require two levels of object creation Require • new an array • new array’s elements - objects elements TotalArea Run EE3206/EE5805 Java Programming & Applications EE3206/EE5805 42 Introduction to Useful Classes Date Random Random EE3206/EE5805 Java Programming & Applications EE3206/EE5805 43 The Date Class The Date You can use the java.util.Date class to create an instance for the current date and time and use its toString method to return the date and time as a string. For example, java.util.Date date = new java.util.Date(); System.out.println(date.toString()); Outputs a string representation of the date like: Wed Sep 30 14:35:46 CST 2009 java.util.Date +Date() +Date(elapseTime: long) +toString(): String +getTime(): long +setTime(elapseTime: long): void Constructs a Date object for the current time. Constructs a Date object for a given time in milliseconds elapsed since January 1, 1970, GMT. Returns a string representing the date and time. Returns the number of milliseconds since January 1, 1970, GMT. Sets a new elapse time in the object. 44 The + sign indicates public modifer EE3206/EE5805 Java Programming & Applications EE3206/EE5805 The Random Class The Random You have used Math.random() to obtain a random double value You Math.random to between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class. java.util.Random class. java.util.Random +Random() +Random(seed: long) +nextInt(): int +nextInt(n: int): int +nextLong(): long +nextDouble(): double +nextFloat(): float +nextBoolean(): boolean Constructs a Random object with the current time as its seed. Constructs a Random object with a specified seed. Returns a random int value. Returns a random int value between 0 and n (exclusive). Returns a random long value. Returns a random double value between 0.0 and 1.0 (exclusive). Returns a random float value between 0.0F and 1.0F (exclusive). Returns a random boolean value. EE3206/EE5805 Java Programming & Applications EE3206/EE5805 45 Random Class Example If two Random objects have the same seed, they will generate If Random objects identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3. Random Random random1 = new Random(3); System.out.print("From random1: "); for (int i = 0; i < 10; i++) System.out.print(random1.nextInt(1000) + " "); Random random2 = new Random(3); System.out.print("\nFrom random2: "); for (int i = 0; i < 10; i++) System.out.print(random2.nextInt(1000) + " "); From random1: 734 660 210 581 128 202 549 564 459 961 From From random2: 734 660 210 581 128 202 549 564 459 961 From EE3206/EE5805 Java Programming & Applications EE3206/EE5805 46 More Examples EE3206/EE5805 Java Programming & Applications EE3206/EE5805 47 Example: The Course Class Example: The Course -name: String -students: String -numberOfStudents: int +Course(name: String) +getName(): String The name of the course. The students who take the course. The number of students (default: 0). Creates a Course with the specified name. Returns the course name. +addStudent(student: String): void Adds a new student to the course list. +getStudents(): String Returns the students for the course. +getNumberOfStudents(): int Returns the number of students for the course. TestCourse Run EE3206/EE5805 Java Programming & Applications EE3206/EE5805 48 Example: The Loan Class Example: The Loan -annualInterestRate: double -numberOfYears: int -loanAmount: double -loanDate: Date +Loan() +Loan(annualInterestRate: double, numberOfYears: int, loanAmount: double) +getAnnualInterestRate(): double +getNumberOfYears(): int +getLoanAmount(): double +getLoanDate(): Date The annual interest rate of the loan (default: 2.5). The number of years for the loan (default: 1) The loan amount (default: 1000). The date this loan was created. Constructs a default Loan object. Constructs a loan with specified interest rate, years, and loan amount. Returns the annual interest rate of this loan. Returns the number of the years of this loan. Returns the amount of this loan. Returns the date of the creation of this loan. +setAnnualInterestRate( Sets a new annual interest rate to this loan. annualInterestRate: double): void Sets a new number of years to this loan. +setNumberOfYears( numberOfYears: int): void +setLoanAmount( loanAmount: double): void +getMonthlyPayment(): double +getTotalPayment(): double Sets a new amount to this loan. Returns the monthly payment of this loan. Returns the total payment of this loan. TestLoanClass Run EE3206/EE5805 Java Programming & Applications EE3206/EE5805 49 ...
View Full Document

Ask a homework question - tutors are online