Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 4-1 Chapter 4 (a) Defining Classes

2 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

3 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!

4 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)

5 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.

6 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 obj ects s1 and s2 are references to pointers and not the actual values of the object

8 4-8 Testing objects for equality, another example When it is executed System.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, but s1 and s2 point (refer) to the same representation. Thus s1 and s2 are equivalent 22"s1 pastel"s2

9 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

10 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();

11 A General form of a Class public class Class-name { //Declare instance variables for class private class identifier ; private primitive-type identifier ; // Class constructor is next public 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

12 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

13 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);

14 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)

15 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

16 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

17 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

18 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

19 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);

20 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", ); 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

21 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

22 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()

23 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

24 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

25 4-25 Case Studies

26 4-26 Classes 4 (b) Instantiation of a class - Objects

27 4-27 Consider Statements int numberOfStudents = 173; This is a primitive variable String 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

28 message numberOfStudents The value of String variable message is a reference to a String object representing the character string I am a student! Operations (methods) The value of primitive int variable numberOfStudents is 173 Operations + - * / length() :int charAt(inti) :char subString(intm,intn) String indexOf(String s,intm) :int... String - text = I am a student!" - length = Representation

29 4-29 Example Consider String a = I am a student!; String b = a; What is the representation? a b I am a student!

30 4-30 Example Next Consider String 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

31 4-31 Example Next Consider the additional assignment String 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!

32 4-32 Example Next Consider the additional assignment String 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.

33 4-33 Example - Rectangle 3x 4y Rectangle: r 5width height2 r 5 2 (3, 4) The third and fourth parameters of the Rectangle constructor specify the dimensions of the new Rectangle The first two parameters of the Rectangle constructor specify the position of the upper-left-hand corner of the new Rectangle intx = 3; inty = 4; intwidth = 5; intheight = 2; Rectangle r =newRectangle(x, y, width, height); primitive variables object variable

34 4-34 Assignment of new Rectangle object Rectangle: rect rect 6 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);

35 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

36 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"

37 4-37 Final variables - immutability The String value is said to be immutable String WARNING = Danger is red"; Danger is red" The contents are immutable because there are no String methods that allow the contents to be changed The reference cannot be modified once it is established WARNING

38 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 method setLocation

39 4-39 final variables - Rectangle object - mutablility Methods setLocation and resize are known as mutors of the object Rectangle. The reference cannot be modified once it is established The contents are mutable because there are Rectangle methods that allow the contents to be changed


Download ppt "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."

Similar presentations


Ads by Google