Download presentation
Presentation is loading. Please wait.
1
Chapter 7 Objects and Classes
2
OO Programming Concepts
An Object corresponds to entity in the real world. Each object has a unique identity state – properties that can change in value behaviors – what can the object do?
3
OO Programming Concepts
An object encapsulates (wraps together) attributes (data) behaviors (methods) Goal: Information Hiding
4
OOP Interface - what the object can do, proper usage vs.
Implementation – how the object works
5
Objects An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.
6
Classes Classes define objects of the same type. Class consists of
Variables – data Methods – behavior
7
Constructors Methods that are used to instantiate a class
Have the same name as the class Do not return a value Note: a method can have the same name as the class and have a return type - It’s not a constructor!
8
Classes
9
UML Class Diagram
10
Constructors Constructors are a special kind of methods that are invoked to construct objects. Circle() { } Circle(double newRadius) { radius = newRadius;
11
Constructors, cont. Constructors · have the same name as class
· have no return type—not even void · invoked using new operator at object creation Constructors initialize objects. Constructors can be overloaded.
12
Creating Objects Using Constructors
new ClassName(); Example: new Circle(); new Circle(5.0);
13
Default Constructor A class may be declared without constructors.
A constructor with no parameters is referred to as a no-arg constructor. No-arg constructor with empty body is implicitly declared. This default constructor is provided automatically only if no constructors are explicitly declared.
14
Declaring Object Reference Variables
To reference an object, assign the object to a reference variable. Syntax: ClassName objectRefVar; Example: Circle myCircle;
15
Declaring/Creating Objects in a Single Step
ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); Assign object reference Create an object
16
Dot Operator Referencing the object’s data: objectRefVar.data
e.g., myCircle.radius Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()
17
A Simple Circle Class Objective: Demonstrate creating objects, accessing data, and using methods. TestCircle1 Run
18
Trace Code animation Declare myCircle
Circle myCircle = new Circle(5.0); SCircle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value
19
Trace Code, cont. animation Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value Create a circle
20
Assign object reference to myCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value Assign object reference to myCircle
21
Trace Code, cont. Declare yourCircle animation
Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle no value Declare yourCircle
22
Create a new Circle object
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle no value Create a new Circle object
23
Assign object reference to yourCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle reference value Assign object reference to yourCircle
24
Change radius in yourCircle
animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value yourCircle reference value Change radius in yourCircle
25
Caution We use Math.methodName(arguments)
(e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using Circle.getArea()? NO! All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).
26
Reference Data Fields The data fields can be of primitive types OR
reference types - Composition of objects For example, the following Student class contains a data field name of the String type. public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value '\u0000' }
27
The null Value If data field of reference type does not reference any object, it holds a special literal value, null.
28
Default Values Data fields of an object have default values. Variables defined in a method do not assume default values.
29
Default Value for a Data Field
Default value of data field: null for reference type 0 for a numeric type false for a boolean type '\u0000' for char type. public class Test { public static void main(String[] args) { Student student = new Student(); System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); }
30
Example Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); } Compilation error: variables not initialized
31
Differences between Variables of Primitive Data Types and Object Types
32
Copying Variables of Primitive Data Types and Object Types
33
Garbage Collection An assignment statement such as c1=c2 results in 2 objects pointing to the same object. The object previously referenced by c1 is no longer referenced so it is garbage. Garbage is automatically collected by JVM.
34
Garbage Collection, cont
TIP: If an object is no longer needed, explicitly assign null to a variable that references the object. The JVM automatically collects the space of an object not referenced by any variable.
35
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.
36
The Date Class Example For example, the following code
java.util.Date date = new java.util.Date(); System.out.println(date.toString()); displays a string like Sun Mar 09 13:50:19 EST
37
The Random Class You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class.
38
The Random Class Example
If two Random objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3. 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: "); System.out.print(random2.nextInt(1000) + " "); From random1: From random2:
39
Instance Variables, and Methods
Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class. The dot operator
40
Static Variables, Constants, and Methods
Static variables are shared by all the instances of the class, class-wide information. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.
41
Static Variables, Constants, and Methods, cont.
To declare static variables, constants, and methods, use the static modifier. The members of the math class are defined as static. That’s why we never create an object of type Math, yet we can use its methods.
42
Static Variables, Constants, and Methods, cont.
43
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 numberOfObjects to track the number of Circle objects created. Circle2 TestCircle2 Run
44
Final instance variables
A final variable is not modifiable. A constant can be initialized In its declaration By constructors Syntax error: not initializing constant variable at declaration or in every constructor.
45
Access to a Class Access level modifiers determine whether other classes can use a particular field OR or invoke a particular method.
46
Access Control Top Level Member Level Public
Package-private (no explicit modifier) Member Level Private Protected – in any subclass or within package
47
Access Levels Modifier Class Package Subclass World Public Y Protected
N No modifier Private
48
Visibility Modifiers and Accessor/Mutator Methods
By default, the class, variable, or method can be accessed by any class in the same package. 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.
50
Top Level Access Modifiers
Member Level Access Modifiers
51
NOTE An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).
52
Summary Modifier Access Private within class within package Public
unrestricted access
53
Why Data Fields Should Be private?
To protect data. To make class easy to maintain.
54
Private Variables How can private data be used by other objects?
Accessor (get) methods To read private data Mutator (set) methods To modify private data
55
Example of Data Field Encapsulation
Circle3 TestCircle3 Run
56
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, essentially pass by reference) TestPassObject Run
57
Passing Objects to Methods, cont.
58
This An object can access a reference to itself: keyword this
Method can declare a local variable with same name as a field. Local variable shadows field Use this.field_name to access field A constructor can invoke another constructor of the same class. this (parameter_list);
59
Reference the Hidden Data Fields
60
Calling Overloaded Constructor
61
Array of Objects Array of objects: array of reference variables.
Circle[] circleArray = new Circle[10]; Array of objects: array of reference variables. Invoking circleArray[1].getArea() involves two levels of referencing. circleArray references to the entire array. circleArray[1] references to a Circle object.
62
Array of Objects, cont. Circle[] circleArray = new Circle[10];
63
Summarizing the areas of the circles
Array of Objects, cont. Summarizing the areas of the circles TotalArea Run
64
Packages Manage complexity of applications Software reuse – import
Unique class names Import classes that are in a different package.
65
Packages Definition: Compilation (with directory setup) Usage:
package package_name; //first line of code The class file is stored in package_name Compilation (with directory setup) Javac –d directory_above_package source_file Usage: import package_name;
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.