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.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Basic Java Constructs and Data Types – Nuts and Bolts
18 January 2013Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Introduction to Programming
Introduction to Programming Java Lab 2: Variables and Number Types 1 JavaLab2 lecture slides.ppt Ping Brennan
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.
Lecture 6 Strings and more I/O COMP1681 / SE15 Introduction to Programming.
Java
Data Structures ADT List
Programming Methodology (1). public class Hello { public static void main(String[] args) { System.out.println("Hello world"); } } Hello world.
EXAMPLES (Arrays). Example Many engineering and scientific applications represent data as a 2-dimensional grid of values; say brightness of pixels in.
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
1 Arrays An array is a special kind of object that is used to store a collection of data. The data stored in an array must all be of the same type, whether.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
 A string is an array of characters.  Strings must have a 0 or null character after the last character to show where the string ends.  The null character.
Computer Programming Lab(7).
Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
String Pemrograman Berbasis Obyek Oleh Tita Karlita.
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
CS110 Programming Language I
Strings in Java 1. strings in java are handled by two classes String &
Strings Testing for equality with strings.
MSc IT Programming Methodology (2). number name number.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
AP Computer Science TOPICS TO DISCUSS.equals() == instanceof operator compareTo Interfaces Abstract Classes.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
1 Various Methods of Populating Arrays Randomly generated integers.
Computer Programming Lab 8.
Java Strings in 10 minutes
Implementing Classes Learning objectives By the end of this lecture you should be able to: design classes using the notation of the Unified Modeling Language.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Java Syntax Primitive data types Operators Control statements.
Strings Reading for this Lecture, L&L, 3.2. Strings String is basically just a collection of characters. Thus, the string “Martyn” could be thought of.
© The McGraw-Hill Companies, 2006 Chapter 6 Classes and objects.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
MSc IT Programming Methodology (2). Oblong EasyScanner BankAccount.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Introduction to Java Java Translation Program Structure
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
CSI 3125, Preliminaries, page 1 String. CSI 3125, Preliminaries, page 2 String Class Java provides the String class to create and manipulate strings.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
(Dreaded) Quiz 2 Next Monday.
Introduction to programming in java
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
Chapter 7: Strings and Characters
Introduction to Object-Oriented Programming
Presentation transcript:

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.

Dealing with complexity

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

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

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.

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.

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

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

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

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

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

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

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

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

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

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 } }

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

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.

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

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

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

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

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

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

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

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.

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

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

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

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

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

Account number: Account name: Susan Richards Current balance:

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];

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

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

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

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

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

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