Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the.

Similar presentations


Presentation on theme: "Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the."— Presentation transcript:

1 Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the concept of encapsulation; explain the terms class and object; create objects in Java; call the methods of an object; Use a number of methods of the String class; create and use arrays of objects.

2 Dealing with complexity

3 Structured programming boolean light; String roomNumber int mark; // switch on light // get building // check if passed main

4 Object-oriented programming boolean light; String roomNumber int mark; // switch on light // get building // check if passed Room Student Projector

5 Classes A class is the blueprint from which objects are generated; Student data methods Class Objects Student s1; Student s2; Student s3; Student s4; A class can also be thought of as a type! ? When we use a class as a data type, we need information about its methods only.

6 Creating Objects Robot ? moveRight(int) moveLeft(int) moveUp(int) moveDown(int) Robot( )int, int Robot r1; r1 = new Robot(5, 50); Robot r2; r2 = new Robot(10, 2); r1.moveRight(20); r2.moveDown(25); A constructor is a special method that generates an object from a class.

7 Effect on computer memory Robot r1 ; Computer MemoryJava Instructions r1 This is the space for the new Robot object r1 = new Robot( 5, 50); null

8 Pre-defined Java classes We have already been using a few pre-defined classes in our programs: Scanner String

9 Revisiting the Scanner and String classes To create a Scanner object we call the Scanner constructor: Scanner sc = new Scanner (System.in); The String class is different from all other classes in Java. We can create String objects without a call to a constructor: String s = “Wednesday”;new String (“Wednesday”);

10 Revisiting the Scanner and String classes We also used methods of the Scanner and String classes. int x = sc.nextInt(); String s = sc.next(); char reply = sc.next().charAt(0);

11 charAt Accepts an integer and returns the character at that position in the string. Note that indexing starts from zero, not 1! An item of type int An item of type char length Returns the length of the string. None An item of type int substring Accepts two integers (eg m and n) and returns a copy of a chunk of the string, from position m to position n-1. Two items of type int A String object concat Accepts a string and returns a new string consisting of the that string joined to the end of the original string. A String object MethodDescriptionInputsOutput

12 toUpperCase Returns a copy of the original string, all upper case. None A String object toLowerCase Returns a copy of the original string, all lower case. None A String object compareTo Accepts a string and compares it to the object's string. It returns zero if the strings are identical, a negative number if the object's string comes first in the alphabet, and a positive number if it comes later. A String object An item of type int. equals Accepts an object and compares this to this to the string. It returns true if these are identical, otherwise returns false. An object of any class A boolean value. MethodDescriptionInputsOutput

13 import java.util.*; public class StringTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = new String(); System.out.print("Enter a string: "); str = sc.next(); System.out.println("The length of the string is " + str.length() ); System.out.println("The character at position 3 is " + str.charAt(2) ); System.out.println("Characters 2 to 4 are " + str.substring(1,4) ); System.out.println( str.concat(" was the string entered") ); System.out.println("This is upper case: " + str.toUpperCase() ); System.out.println("This is lower case: " + str.toLowerCase() ); } }

14 Enter a string:Europe The length of the string is 6 The character at position 3 is r Characters 2 to 4 are uro Europe was the string entered This is upper case: EUROPE This is lower case: europe RUN import java.util.*; public class StringTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = new String(); System.out.print("Enter a string: "); str = sc.next(); System.out.println("The length of the string is " + str.length()); System.out.println("The character at position 3 is " + str.charAt(2)); System.out.println("Characters 2 to 4 are " + str.substring(1,4)); System.out.println(str.concat(" was the string entered")); System.out.println("This is upper case: " + str.toUpperCase()); System.out.println("This is lower case: " + str.toLowerCase()); }

15 Comparing strings When comparing two objects, such as Strings, we should do so by using a method called equals ; We should not use the equality operator (==); if(firstString == secondString) { // more code here } String firstString = “Hello”; String secondString = “Goodbye”; if(firstString.equals(secondString))

16 import java.util.*; public class StringComp { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String string1, string2; int comparison; System.out.print("Enter a String: "); string1 = sc.next(); System.out.print("Enter another String: "); string2 = sc.next(); comparison = string1.compareTo(string2) ; // check comparison } }

17 if (comparison < 0) { System.out.println(string1 + " comes before " + string2 + " in the alphabet"); } else if (comparison > 0) { System.out.println(string2 + " comes before " + string1 + " in the alphabet"); } else { System.out.println("The strings are identical"); } RUN Enter a String: Enter another String: goodbye comes before hello in the alphabet hello goodbye

18 Using some classes written for you We have written some classes for you to use: Oblong EasyScanner BankAccount Next week we will show you how we wrote them.

19 Methods of the Oblong class The constructor. Takes two items of data, both of type double, representing the length and height of the oblong respectively. Oblong Oblong myOblong = new Oblong(12.5, 20);

20 Methods of the Oblong class Takes an item type double and re-sets the length of the oblong. Returns no value. setLength myOblong.setlength(17.5);

21 Methods of the Oblong class Takes an item type double and re-sets the height of the oblong. Returns no value. setHeight myOblong.setHeight(12);

22 Methods of the Oblong class Takes no parameters and returns the value of the height of the oblong getHeight System.out.println( ); myOblong.getHeight( )

23 Methods of the Oblong class Takes no parameters and returns the value of the length of the oblong. getLength System.out.println( ); myOblong.getLength( )

24 Methods of the Oblong class Takes no parameters and returns the area of the oblong. calculateArea System.out.println( ); myOblong.calculateArea( )

25 Methods of the Oblong class Takes no parameters and returns the perimiter of the oblong. calculatePerimeter System.out.println( ); myOblong.calculatePerimeter( )

26 The EasyScanner class Issues with using the Scanner class for keyboard input it is necessary to create a new Scanner object in every method that uses the Scanner class; there is no simple method such as nextChar for getting a single character like there is for the int and double types; the next method doesn't allow us to enter strings containing spaces.

27 The input methods of the EasyScanner class Java type EasyScanner method intnextInt() doublenextDouble() charnextChar() StringnextString()

28 Examples of using EasyScanner char c; System.out.print("Enter a character: "); c = EasyScanner.nextChar(); String s; System.out.print("Enter a string: "); c = EasyScanner.nextString();

29 The BankAccount class Contains methods to process bank accounts. BankAccount Susan Richards Sumana Khan 150.0

30 The methods of the BankAccount class MethodDescriptionInputsOutput BankAccount A constructor. It accepts two strings and assigns them to the account number and account name respectively. It also sets the account balance to zero. Two String objects Not applicable getAccountNumber Returns the account number.NoneAn item of type String getAccountName Returns the account name.NoneAn item of type String getBalance Returns the balance.NoneAn item of type double deposit Accepts an item of type double and adds it to the balance An item of type double None withdraw Accepts an item of type double and subtracts it from the balance An item of type double None

31 public class BankAccountTester { public static void main(String[ ] args) { BankAccount account1 = new BankAccount(" ","Susan Richards"); account1.deposit(1000); System.out.println("Account number: " + account1.getAccountNumber()); System.out.println("Account name: " + account1.getAccountName()); System.out.println("Current balance: " + account1.getBalance()); } }

32 Account number: Account name: Susan Richards Current balance:

33 Arrays of objects If we have to process many BankAccount objects, we can create an array of BankAccount s. int[] someArray = new int[3]; An array of integers An array of BankAccount objects BankAccount[] accountList = new BankAccount[3];

34 The effect on memory of creating an array of objects null accountList accountList = new BankAccount [3]; reference to bank account Java instructionComputer memory BankAccount[] accountList; null

35 Adding bank accounts to the array accountList[0] = new BankAccount(" ","Susan Richards"); accountList[1] = new BankAccount(" ","Delroy Jacobs"); accountList[2] = new BankAccount(" ","Sumana Khan");

36 accountList[1] the BankAccount object with account number " " and name "Sumana Khan" accountList[2] accountList[0] the BankAccount object with account number " " and name "Susan Richards" the BankAccount object with account number " " and name "Delroy Jacobs" accountList

37 Accessing objects in an array accountList[0].deposit(1000); returns a BankAccount object calls a BankAccount method accountList[0].withdraw(500); accountList[2].deposit(150);

38 public class BankAccountTester2 { public static void main(String[] args) { BankAccount[] accountList = new BankAccount[3]; accountList[0] = new BankAccount(" ","Susan Richards"); accountList[1] = new BankAccount(" ","Delroy Jacobs"); accountList[2] = new BankAccount(" ","Sumana Khan"); accountList[0].deposit(1000); accountList[2].deposit(150); accountList[0].withdraw(500); for(BankAccount item : accountList) { System.out.println("Account number: " + item.getAccountNumber()); System.out.println("Account name: " + item.getAccountName()); System.out.println("Current balance: " + item.getBalance()); System.out.println(); } } }

39 Account number: Account name: Susan Richards Current balance: Account number: Account name: Delroy Jacobs Current balance: 0.0 Account number: Account name: Sumana Khan Current balance: 150.0


Download ppt "Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the."

Similar presentations


Ads by Google