UFCE3T-15-M Object-oriented Design and Programming Block1: Objects and Classes Jin Sa 27-Sep-05 UFCE3T-15-M Programming part 1
Objectives To understand objects and classes and use classes to model objects. To learn how to declare a class and how to create an object of a class. To understand the roles of constructors and use constructors to create objects. To distinguish between object reference variables and primitive data type variables. To use classes in the Java library. To declare private data field with appropriate get and set methods. 27-Sep-05 UFCE3T-15-M Programming part 2
Objectives To develop methods with object arguments. To understand the difference between instance and static variables and methods. 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 understand the use of various visibility modifiers. To apply class abstraction to develop software. 27-Sep-05 UFCE3T-15-M Programming part 3
OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified, e.g. a student, a desk, a circle. An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields with their current values. The behavior of an object is defined by a set of methods. 27-Sep-05 UFCE3T-15-M Programming part 4
Classes Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Constructors are special methods, which are invoked to construct objects from the class. A class is a template that defines what an object s data and methods will be. An object is an instance of a class. 27-Sep-05 UFCE3T-15-M Programming part 5
Classes 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; Data field/ attributes More than one constructors /** Return the area of this circle */ double findarea() { return radius * radius * 3.14159; Method 27-Sep-05 UFCE3T-15-M Programming part 6
Circle() { Constructors Circle(double newradius) { radius = newradius; Constructors are a special kind of methods that are invoked to construct objects. 27-Sep-05 UFCE3T-15-M Programming part 7
Constructors, cont. A constructor with no parameters is referred to as a no-arg constructor. Constructors must have the same name as the class itself. Constructors do not have a return type not even void. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects. 27-Sep-05 UFCE3T-15-M Programming part 8
Creating Objects Using new ClassName(); Constructors Example: new Circle(); new Circle(5.0); 27-Sep-05 UFCE3T-15-M Programming part 9
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. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class. 27-Sep-05 UFCE3T-15-M Programming part 10
Declaring Object Reference Variables To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: ClassName objectrefvar; Example: Circle mycircle; 27-Sep-05 UFCE3T-15-M Programming part 11
Declaring/Creating Objects in a Single Step ClassName objectrefvar = new ClassName(); Assign object reference Create an object Example: Circle mycircle = new Circle(); 27-Sep-05 UFCE3T-15-M Programming part 12
Accessing Objects Referencing the object s data: objectrefvar.data e.g., mycircle.radius Invoking the object s method: objectrefvar.methodname(arguments) e.g., mycircle.findarea() 27-Sep-05 UFCE3T-15-M Programming part 13
Example: Using Objects Objective: Demonstrate creating objects, accessing data, and using methods. (run../sourcecode/codeblock1/testsimplecircle.java) 27-Sep-05 UFCE3T-15-M Programming part 14
// SimpleCircle class has two constructors class SimpleCircle { double radius; /** Construct a circle with radius 1 */ SimpleCircle() { radius = 1.0; /** Construct a circle with a specified radius */ SimpleCircle(double newradius) { radius = newradius; /** Return the area of this circle */ double findarea() { return radius * radius * 3.14; 27-Sep-05 UFCE3T-15-M Programming part 15
public class TestSimpleCircle { /** Main method */ public static void main(string[] args) { // Create a circle with radius 5.0 SimpleCircle mycircle = new SimpleCircle(5.0); System.out.println("The area for radius" + mycircle.radius + " is "+mycircle.findarea()); // Create a circle with radius 1 SimpleCircle yourcircle = new SimpleCircle(); System.out.println(...); // Modify circle radius yourcircle.radius = 100; System.out.println(...); 27-Sep-05 UFCE3T-15-M Programming part 16
Differences between Variables of rimitive Data Types and Object Types Primitive type int i = 1 i 1 Created using new Circle() Object type Circle c c reference c: Circle radius = 1 27-Sep-05 UFCE3T-15-M Programming part 17
Copying Variables of Primitive Data Types and Object Types Primitive type assignment i = j Object type assignment c1 = c2 Before: After: Before: After: i 1 i 2 c1 c1 j 2 j 2 c2 c2 c1: Circle c2: Circle radius = 5 radius = 9 27-Sep-05 UFCE3T-15-M Programming part 18
Using Classes from the Java Library We declared the Circle class and created objects from the class. Often you will use the classes in the Java library to develop programs. 27-Sep-05 UFCE3T-15-M Programming part 19
Use of Math class in Java.lang class SimpleCircle { double radius;... /** Return the area of this circle */ double findarea() { return (radius * radius * Math.PI); 27-Sep-05 UFCE3T-15-M Programming part 20
The Date Class Java provides a system-independent encapsulation of date and time in the java.util.date class. You can use the 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. 27-Sep-05 UFCE3T-15-M Programming part 21
Use the Date class For example, the following code java.util.date date = new java.util.date(); System.out.println(date.toString()); displays a string like Tue Sep 27 13:50:19 EST 2005. 27-Sep-05 UFCE3T-15-M Programming part 22
Visibility Modifiers public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class. By default, the class, variable, or method can accessed by any class in the same package. 27-Sep-05 UFCE3T-15-M Programming part 23
package p1; public class C1 { public int x; int y; private int z; public void m1() { void m2() { private void m3() { public class C2 { 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 { 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(); The private modifier restricts access to within an object, the default modifier restricts access to within a package, and the public modifier enables unrestricted access. 27-Sep-05 UFCE3T-15-M Programming part 24
Why Data Fields Should Be private? To protect data. To make class easy to maintain. 27-Sep-05 UFCE3T-15-M Programming part 25
Example of Data Field Encapsulation In this example, private data are used for the radius and the accessor (or get and set) methods getradius and setradius are provided for the clients to retrieve and modify the radius. 27-Sep-05 UFCE3T-15-M Programming part 26
public class Circle { private double radius; // private attribute... /** Use a get method to return radius */ public double getradius() { return radius; /** Use a set method to set a new radius */ public void setradius(double newradius) { radius = (newradius >= 0)? newradius : 0;... 27-Sep-05 UFCE3T-15-M Programming part 27
// TestCircle.java: Demonstrate private modifier public class TestCircle { /** Main method */ public static void main(string[] args) { Circle mycircle = new Circle(5.0); System.out.println("The area for radius " + mycircle.getradius() + " is " + mycircle.findarea()); // Double mycircle's radius mycircle.setradius(mycircle.getradius() * 2); System.out.println("The area radius " + mycircle.getradius() + " is " + mycircle.findarea()); 27-Sep-05 UFCE3T-15-M Programming part 28
Passing Objects to Methods Passing by value for primitive type value (the value is passed to the parameter) Passing by value for reference type value (the value is the reference to the object) 27-Sep-05 UFCE3T-15-M Programming part 29
public class TestPassObject { /** Print a table of areas for radius */ public void printareasupto(circle c, int times) { System.out.println("Radius \t\tarea"); for (int i=0; i<times; i++) { System.out.println(c.getRadius() + "\t\t\t" + c.findarea()); c.setradius(c.getradius() + 1); // end of printareaupto 27-Sep-05 UFCE3T-15-M Programming part 30
/** Main method */ public static void main(string[] args) { // Create a Circle object with radius 1 Circle mycircle = new Circle(); TestPassObject mypassobject = new TestPassObject(); //Print areas for radius 1, 2, 3, 4, 5. mypassobject.printareasupto(mycircle, 5); 27-Sep-05 UFCE3T-15-M Programming part 31
Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class. 27-Sep-05 UFCE3T-15-M Programming part 32
Static (Class) Variables, Constants, and Methods Static variables are shared by all the instances of the class. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class. 27-Sep-05 UFCE3T-15-M Programming part 33
Static Variables, Constants, and Methods, cont. To declare static variables, constants, and methods, use the static modifier. 27-Sep-05 UFCE3T-15-M Programming part 34
Example of Using Instance and Class Variables and Method Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numofobjects to track the number of Circle objects created. 27-Sep-05 UFCE3T-15-M Programming part 35
public class CircleStatic { private double radius; /** The number of the objects created */ private static int numberofobjects = 0; /** Construct a circle with radius 1 */ public CircleStatic() { radius = 1.0; numberofobjects++; public CircleStatic(double newradius) { radius = newradius; numberofobjects++; 27-Sep-05 UFCE3T-15-M Programming part 36
... /** Set a new radius */ public void setradius(double newradius) { radius = newradius; /** Return numberofobjects */ public static int getnumberofobjects() { return numberofobjects; public double findarea() { return radius * radius * Math.PI; 27-Sep-05 UFCE3T-15-M Programming part 37
public class TestCircleStatic { /** Main method */ public static void main(string[] args) { CircleStatic circle1 = new CircleStatic(); System.out.println("Circle1 is radius: " + circle1.getradius() + "and number of Circle objects:" + CircleStatic.getNumberOfObjects()); CircleStatic circle2 = new CircleStatic(5); System.out.println("Circle2 is radius: " + circle2.getradius() + "and number of Circle objects:" + CircleStatic.getNumberOfObjects()); 27-Sep-05 UFCE3T-15-M Programming part 38
The this Keyword Use this to refer to the object that invokes the instance method. Use this to refer to an instance data field. 27-Sep-05 UFCE3T-15-M Programming part 39
Example of using this lass Foo { int i = 5; static double k = 0; void seti(int i) { this.i = i; Suppose that f1 and f2 are two objects of Foo Invoking f1.seti(10) is to execute f1.i = 10, where this is replaced by f1 Invoking f2.seti(45) is to execute f2.i = 45, where this is replaced by f2 27-Sep-05 UFCE3T-15-M Programming part 40
Example of using this public class Circle { private double radius; public Circle(double radius) { this.radius = radius; public Circle() { this(1.0); this must be explicitly used to reference the data field radius of the object being constructed this is used to invoke another constructor public double findarea() { return radius * radius * Math.PI; 27-Sep-05 UFCE3T-15-M Programming part 41
Array of Objects Circle[] circlearray = new Circle[10]; An array of objects is actually an array of reference variables. circlearray[1].findarea() involves two levels of referencing. circlearray references to the entire array. circlearray[1] references to a Circle object. 27-Sep-05 UFCE3T-15-M Programming part 42
Array of Objects, cont. Circle[] circlearray = new Circle[10]; circlearray reference circlearray[0] Circle object 0 circlearray[1] Circle object 1 circlearray[9] Circle object 9 27-Sep-05 UFCE3T-15-M Programming part 43
Array of Objects, cont. Example: add up the areas of the circles 27-Sep-05 UFCE3T-15-M Programming part 44
public class ManyCircles { Circle[] circlearray; public void createcirclearray() { circlearray = new Circle[10]; for (int i = 0; i < circlearray.length; i++) { circlearray[i] = new Circle(Math.random() * 100); public void printcirclearray() { System.out.println("Radius\t\t\t\t" + "Area"); for (int i = 0; i < circlearray.length; i++) { System.out.print(circleArray[i].getRadius() + "\t\t" + circlearray[i].findarea() + '\n'); 27-Sep-05 UFCE3T-15-M Programming part 45
/** Add circle areas */ public void sumarray() { // Initialize sum double sum = 0; // Add areas to sum for (int i=0; i<circlearray.length; i++) sum += circlearray[i].findarea(); System.out.println( "The area of all the circles: "+ sum); 27-Sep-05 UFCE3T-15-M Programming part 46
/** Main method */ public static void main(string[] args) { ManyCircles allcircles = new ManyCircles(); // Create circlearray allcircles.createcirclearray(); // Print circlearray allcircles.printcirclearray(); // Print total areas of the circles allcircles.sumarray(); 27-Sep-05 UFCE3T-15-M Programming part 47
Class Abstraction and Encapsulation 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 encapsulated and hidden from the user using the visibility modifiers. 27-Sep-05 UFCE3T-15-M Programming part 48