4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition...
-
Upload
samuel-doyle -
Category
Documents
-
view
214 -
download
1
Transcript of 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition...
![Page 1: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/1.jpg)
4-1
Chapter 4 (a)
Defining Classes
![Page 2: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/2.jpg)
4-2
The Contents of a Class Definition
• A class definition specifies the data items and methods that all of its objects will have
• Data items are called fields or instance variables
• Instance variable declarations and method definitions can be placed in any order within the class definition
![Page 3: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/3.jpg)
4-3
Working with objects
• When manipulating primitive variable, such as real numbers, we obtain results that would follow our expectation
• When dealing with objects we have a new experience!
![Page 4: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/4.jpg)
4-4
Using == with Strings
• The equality comparison operator (==) can correctly test two values of a primitive type
• However, when applied to two objects such as objects of the String class, == tests to see if they are stored in the same memory location, not whether or not they have the same value
• In order to test two strings to see if they have equal values, use the method equals, or equalsIgnoreCase
string1.equals(string2)
string1.equalsIgnoreCase(string2)
![Page 5: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/5.jpg)
4-5
Objects - storage
• To date we have only considered variable based on primitives, that is integer, real numbers, characters, Boolean.
x = 2; means that the value 2 is stored in the variable x.
If we have an object such as String then String colour;colour = “red”; does not mean that red is stored in the
object colour.
![Page 6: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/6.jpg)
4-6
First look at objects -Testing objects for equality
• Objects are String, rectangle, etc.• Consider
System.out.print("Enter a string: ");String s1 = stdin.readLine();System.out.print("Enter another string: ");String s2 = stdin.readLine();
if (s1 == s2) {System.out.println("Same");
}else {
System.out.println("Different");} What is the output if the user enters ”22" both times?
For objects s1 and s2 are references to pointers and not the actual values of the object
![Page 7: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/7.jpg)
4-7
Testing objects for equality
• When it is executedSystem.out.print("Enter a string: ");String s1 = stdin.readLine();System.out.print("Enter another string: ");String s2 = stdin.readLine();
• Memory looks like
• As a result, no matter what is entered s1 and s2 are not the same– They refer to different objects
”22"s1
”22"s2
![Page 8: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/8.jpg)
4-8
Testing objects for equality, another example
• When it is executedSystem.out.print("Enter a string: ");String s1 = stdin.readLine();System.out.print("Enter another string: ");String s2 = stdin.readLine();s1 = s2; // redirect pointer
• Memory now looks like
“22” and “pastel” are different objects, buts1 and s2 point (refer) to the same representation. Thus s1 and s2 are equivalent
”22"s1
”pastel"s2
![Page 9: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/9.jpg)
4-9
Testing objects for equality - (equals)• Now we are testing the values stored for each object.• Consider
System.out.print("Enter a string: ");String s1 = stdin.readLine();System.out.print("Enter another string: ");String s2 = stdin.readLine();
if (s1.equals(s2)) {System.out.println("Same");
}else {
System.out.println("Different");}
Tests whether s1 and s2 represent the same object
All objects have a method equals(). The String equals() method tests for equality in representation
![Page 10: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/10.jpg)
4-10
The new Operator (as with Scanner)
• An object of a class is named or declared by a variable of the class type:
ClassName classVar;
• The new operator must then be used to create the object and associate it with its variable name:
classVar = new ClassName();
• These can be combined as follows:
ClassName classVar = new ClassName();
![Page 11: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/11.jpg)
A General form of a Classpublic class Class-name
{//Declare instance variables for class
private class identifier ;private primitive-type identifier ;
// Class constructor is nextpublic class-name ( parameters )
{//Implementation of constructor goes here
}
//Method(s) is next public return-type method-name-1 ( parameters ) { // Implementation of method goes here
}
} // end of class
![Page 12: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/12.jpg)
public class BankAccount { // instance variables declared
private String my_ID; private double my_balance;
// Constructor to initialize the state public BankAccount(String initID, double initBalance ) { my_ID = initID; my_balance = initBalance; } // methods
public void deposit(double depositAmount) // Method (modifier){ // Credit this account by depositAmount
my_balance = my_balance + depositAmount;}
public void withdraw(double withdrawalAmount) // Method (modifier) { // Debit this account by withdrawalAmount my_balance = my_balance - withdrawalAmount;
}} // end of class
An example – a Class BankAccount
![Page 13: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/13.jpg)
4-13
Methods – A Java class may contains many methods (operations):
• Method headings specify the number and type of arguments required
• There are two major components to a method: – the method heading– the block (a set of curly braces with the code that completes the
method's responsibility)
• There are two different kinds of method:(i) an instance method, an operation on an object(ii) a class method, which is unable to operate on an object. This
is also known as a static method (section 4)
eg. instance method: shape.myRectangle.paint(red); class method: math.sqrt(x);
![Page 14: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/14.jpg)
4-14
Static and non-Static Methods • Thus a static method is one that can be used without
a calling object• A static method still belongs to a class, and its
definition is given inside the class definition• A static method cannot refer to an instance variable
of the class, and it cannot invoke a non-static method of the class– A static method can invoke another static method,
however
• A non-static method can refer to an instance variable of the class (see slides later in this section)
![Page 15: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/15.jpg)
4-15
The Class
– Virtually all classes have the following in common:
private instance variables store the state of the objects
constructors initialise the state of an object
some messages modify the state of objects
some messages provide access to the state of objects
![Page 16: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/16.jpg)
Objects are about Operations and State– The methods declared public are the
messages that may be sent to any instance of the class, the objects
– The instance variables declared private store the state of the objects
• private means no direct access from outside the class
– Every instance of a class has it own separate state
• We could have 5234 BankAccount objects, then we would have 5234 IDs and 5234 balances
![Page 17: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/17.jpg)
4-17
Instance Variables– The state of an object is stored as instance variables
• these are the variables that are declared inside the class, but outside of the method bodies
• each instance of the class has its own set of instance variables with 954 objects you have 954 sets of instance variables
• all methods in the class have access to instance variables– and most methods will reference at least one of the instance variables,
thus, the data and methods are related
• when declared private, no one else can access the instance variables the state is encapsulated, nice and safe behind methods
![Page 18: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/18.jpg)
4-18
Method Parameters (formal)
• A parameter list provides a description of the data required by a method
– It indicates the number and types of data pieces needed, the order in which they must be given, and the local name for these pieces as used in the method
public double myMethod(int p1, int p2, double p3) { method body}
– These parameters are also called formal parameters
![Page 19: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/19.jpg)
4-19
Actual Parameters• When a method is invoked, the appropriate values must be
passed to the method in the form of arguments
– Arguments are also called actual parameters
• The number and order of the arguments must exactly match that of the formal parameter list
• The type of each argument must be compatible with the type of the corresponding parameter
int a=1,b=2;
double c=3;
double result = myMethod(a,b,c);
![Page 20: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/20.jpg)
4-20
Constructors– Constructor
• a special method that initializes the state of objects• gets invoked when you construct an object• has the same name as the class• does not have a return type
– a constructor returns a reference to the instance of the class
– Here is a call to a constructor:
BankAccount kateyAcct = new BankAccount( "Katey", 10.00 );
• What is the action carried out?– The constructor initializes the instance variables using the statements
my_ID = initID; my_balance = initBalance;
Giving
my_ID the value Katey my_balance the value £10
![Page 21: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/21.jpg)
4-21
Default Constructor
• If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created
• If you include even one constructor in your class, Java will not provide this default constructor
• If you include any constructors in your class, be sure to provide your own no-argument constructor as well
![Page 22: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/22.jpg)
4-22
The methods equals and toString
• Java expects certain methods, such as equals and toString, to be in almost all, classes
• The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal"– Note: You cannot use == to compare objects public boolean equals(ClassName objectName)
• The purpose of the toString method is to return a String value that represents the data in the object public String toString()
![Page 23: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/23.jpg)
4-23
public and private Modifiers• The modifier public means that there are no restrictions on
where an instance variable or method can be used
• The modifier private means that an instance variable or method cannot be accessed by name outside of the class
• It is considered good programming practice to make all instance variables private
• Most methods are public, and thus provide controlled access to the object
• Usually, methods are private only if used as helping methods for other methods in the class
![Page 24: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/24.jpg)
4-24
Accessor and Mutator Methods
• Accessor methods allow the programmer to obtain the value of an object's instance variables– The data can be accessed but not changed– The name of an accessor method typically starts with the word get
• Mutator methods allow the programmer to change the value of an object's instance variables in a controlled manner– Incoming data is typically tested and/or filtered– The name of a mutator method typically starts with the word set
![Page 25: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/25.jpg)
4-25
Case Studies
![Page 26: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/26.jpg)
4-26
Classes 4 (b)
Instantiation of a class - Objects
![Page 27: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/27.jpg)
4-27
Consider
• Statementsint numberOfStudents = 173;
This is a primitive variableString message = ”I am a student!“
This is an object variable
• How do we represent these definitions according to the notions of Java?
message ”I am a student!"
Message is a “header” that points to a memory location
![Page 28: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/28.jpg)
4-28
173
message
numberOfStudents
The value of Stringvariable messageis a reference to a
String objectrepresenting thecharacter string”I am a student!”
Operations(methods)
The value of primitive intvariable numberOfStudents is 173Operations + - * /
length() : int charAt( int i) : char subString( int m, int n) String indexOf(String s, int m) : int ...
String
- text = “I am a student!"- length = 15- ...
Representation
![Page 29: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/29.jpg)
4-29
Example
• ConsiderString a = ”I am a student!“;String b = a;
• What is the representation?
a
b
”I am a student!“
![Page 30: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/30.jpg)
4-30
Example
• Next ConsiderString a = ”I am a student!“;String b = ”I am also a student!“;
• What is the representation?
a
b
”I am a student!“
”I am also a student!“
A and b are different headers pointing (referring) to different areas of computer memory
![Page 31: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/31.jpg)
4-31
Example
• Next Consider the additional assignmentString a = ”I am a student!“;String b = ”I am also a student!“;a = b;
• What is the representation?– both headers, a and b, will now point to the same
memory location.
a
b
”I am a student!“
”I am also a student!“
![Page 32: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/32.jpg)
4-32
Example
• Next Consider the additional assignmentString a = ”I am a student!“;String b = ”I am also a student!“;a = b;
• What is the representation?– both headers, a and b, will now point to the same
memory location.
a
b
”I am a student!“
”I am also a student!“
The string “I am a student!” is not reference (not pointed at).It is no longer required, therefore, that portion of memory is released for other use. This release of memory is known as garbage collection.
![Page 33: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/33.jpg)
4-33
Example - Rectangle
3x
4y
Rectangle: r
5width
height 2
r
5
2(3, 4)
The third and fourthparameters of theRectangle constructorspecify the dimensions ofthe new Rectangle
The first two parameters of theRectangle constructor specify theposition of the upper-left-handcorner of the new Rectangle
int x = 3;int y = 4;int width = 5;int height = 2;Rectangle r = new Rectangle(x, y, width, height);
primitive variables
objectvariable
![Page 34: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/34.jpg)
4-34
Assignment of new Rectangle object
Rectangle: rectrect6
2(1, 1)
• Assignment can be used to give value to an uninitialized object by constructing a new object value.
• Example, a Rectangle object:
Rectangle rect;
//This object is uninitialized, therefore has no memory allocation.
rect = new Rectangle(1,1,6,2);
![Page 35: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/35.jpg)
4-35
final variables (constants)• Consider
final String POEM_TITLE = “Charge of the Light Brigade";
final String WARNING = “Danger is red";
final locks the object reference, but it does not lock what is referenced in the memory location.
• What is the representation?
“Charge of the Light Brigade"POEM_TITLE
”Danger is red"WARNING
The locks indicate the memory reference is constant.Neither POEM_TITLE or WARNING can be pointed elsewhere.
What is held in memory is not locked
![Page 36: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/36.jpg)
4-36
final variables (constants)
• So, can we modify the String held in memory?
final String WARNING = “Danger is green"; No, this is illegal because we are trying to redirect the pointer
“Danger is green"
”Danger is red"WARNING
Not allowed as pointer is locked,due to it being a final variable.
We can change the value in memory if the object has methods which can access the value held.String has methods such as length, but no operations that will actually change the value of “Danger is green"
![Page 37: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/37.jpg)
4-37
Final variables - immutability
• The String value is said to be immutableString WARNING = ”Danger is red";
”Danger is red"
The contents are immutable becausethere are no String methods thatallow the contents to be changed
The reference cannot bemodified once it is
established
WARNING
![Page 38: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/38.jpg)
4-38
final variables - Rectangle object - mutablility
• Consider
final Rectangle BLOCK = new Rectangle(6, 9, 4, 2);BLOCK.setLocation(1, 4);BLOCK.resize(8, 3); // Rectangle methods setLocation
and reSize• Final representation
BLOCK.resize(8, 3);
Rectangle:BLOCK(1, 4)
The new size of the rectangle, (8, 3), has been set by the Rectangle method resize
8
3
The new origin, (1, 4), has been set by the Rectangle methodsetLocation
![Page 39: 4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.](https://reader035.fdocuments.in/reader035/viewer/2022062619/5515e0a055034638038b4bde/html5/thumbnails/39.jpg)
4-39
final variables - Rectangle object - mutablility
• Methods setLocation and resize are known as mutors of the object Rectangle.
Rectangle:BLOCK
8
3(1, 4)
The reference cannot bemodified once it is
established
The contents are mutable becausethere are Rectangle methods thatallow the contents to be changed