Class. Chapter 6: Data Abstraction. Example. Class

Similar documents
Class. Chapter 6: Data Abstraction. Example. Class

In Java there are three types of data values:

Objects: Data Abstraction

Chapter 6. Classes revisited. Objects: Data Abstraction. Data Abstraction

String. Other languages that implement strings as character arrays

Lab 14 & 15: String Handling

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

Data & Functional Abstraction ( (Parts of Chaps 4 & 6) Objects. Classes. In Java there are three types of data values:

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Creating Strings. String Length

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Selected Questions from by Nageshwara Rao

STRINGS AND STRINGBUILDERS. Spring 2019

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.


CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

OOP-Lecture Java Loop Controls: 1 Lecturer: Hawraa Sh. You can use one of the following three loops: while Loop do...while Loop for Loop

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

- Thus there is a String class (a large class)

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Strings! Today! CSE String Methods!

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CHAPTER 6 MOST COMMONLY USED LIBRARIES

More non-primitive types Lesson 06

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)

CS251L REVIEW Derek Trumbo UNM

BM214E Object Oriented Programming Lecture 8

CS-202 Introduction to Object Oriented Programming

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

STUDENT LESSON A10 The String Class

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Lecture Notes for CS 150 Fall 2009; Version 0.5

USING LIBRARY CLASSES

5/23/2015. Core Java Syllabus. VikRam ShaRma

CS 1301 Ch 8, Part A

We now start exploring some key elements of the Java programming language and ways of performing I/O

Java Basic Programming Constructs

AP Computer Science. Strings. Credit: Slides are modified with permission from Barry Wittman at Elizabethtown College

Class Library java.lang Package. Bok, Jong Soon

Lesson:9 Working with Array and String

Programming with Java

Welcome to the Using Objects lab!

Introduction to Programming Using Java (98-388)

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

A variable is a name for a location in memory A variable must be declared

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Index COPYRIGHTED MATERIAL

Advanced Object Concepts

9 Working with the Java Class Library

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSE1710. Big Picture. Today is last day covering Ch 6. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

Prashanth Kumar K(Head-Dept of Computers)

Introduction to Objects. James Brucker

Activity 9: Object-Oriented

Welcome to the Using Objects lab!

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Building Java Programs

Chapter 1 Getting Started

Character Strings COSC Yves Lespérance. Lecture Notes Week 6 Java Strings

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Lecture 15. Arrays (and For Loops)

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

COMP6700/2140 Data and Types

Building Java Programs

More on variables and methods

Points To Remember for SCJP

Introduction to Programming (Java) 4/12

TEXT-BASED APPLICATIONS

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Programming Techniques

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Chapter 8: Strings and Things

Full file at

Pace University. Fundamental Concepts of CS121 1

Review for Test 1 (Chapter 1-5)

Chapter 4 Defining Classes I

"Hello" " This " + "is String " + "concatenation"

Getting started with Java

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Java Strings Java, winter semester

appreciate the difference between a char and a string understand and use the String class methods

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

Strings, Strings and characters, String class methods. JAVA Standard Edition

Java Classes & Primitive Types

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CSC 1214: Object-Oriented Programming

Lecture 5: Methods CS2301

Building Java Programs Chapter 2

Transcription:

Chapter 6: Data Abstraction In Java, there are three types of data values primitives arrays objects actually, arrays are a special type of object Class In Java, objects are used to represent data values Just as 3 is a primitive value of type int, every object must have a type These types are called classes Class A class defines a type of object, including its data: the information that is used to represent the object the operations (methods) that can be performed on the data After the type is defined, objects of that type can be defined and used An individual value of a class is called an object, or an instance of the class Example Suppose we want to represent planets in Java We can define a class Planet, with data: diameter, mass, distance from the sun, orbital period, rotational period, location,... methods: setdiameter, setmass, etc. getdiameter, getmass, etc. move Instances of Planet might include earth, mars, venus, saturn

Objects and Methods Different objects have different methods for manipulating their data The specific methods are determined based on what makes sense for that type of object For example, with strings: length, concatenation, comparison, substring String: A standard class String is a standard Java class Remember, values from a class are called objects, so "hello" is an object from the class String, or an instance of the class The class String has instance methods that operate on an instance of the class For example: length(), concat(), compareto(), charat() Methods Each type of object supports a specified set of methods There are two types of methods in a class instance methods class methods Instance Methods Instance methods are called for a specific object and have direct access to that object s data without having to pass the object as a parameter String s = "abc"; s.length(); The object is implicitly passed as a parameter to the method. We use the object's name followed by a '.', followed by the method name

String Instance Methods boolean equals( Object anobject ) compares this String with another object not the same as '==' See StringCompare.java int length() Number of characters in this String char charat( int index ) The character at position index in this String index ranges from 0 to length() - 1 IndexOutOfBoundsException String Instance Methods 2 int compareto(string str) Returns an integer value, based on lexicographic order int indexof(int ch) Index of where the first occurrance of ch occurs in this string or -1 if not present int indexof(string str) Index of the first character of a matching substring str or -1 if not present String Instance Methods 3 String concat(string str) Concatenates this string instance with str and returns the result String tolowercase() Returns a copy of this string, but converted to all lower case String touppercase() Returns a copy of this string, but converted to all upper case Class Methods These methods are part of the class definition, but don't operate on a specific instance of the class Class methods are indicated by the keyword static We have written class methods up to now Class methods provide some type of operation related to the objects provided by the class Math.random() Math.sqrt()

String.valueOf() static String valueof( type prim ) returns the String representation of the value of prim valueof is an overloaded function valueof( char c ) valueof( char[] data ) valueof( int i ) valueof( double d ) String.valueOf() static String valueof( type prim ) We don't need an instance of String to call this method Instead, we use the class name: String s; int value = 1234; s = String.valueOf( value ); System.out.println( s.length() ); StringTest.java // StringTest.java - demo some String methods public class StringTest { public static void main(string[] args) { String str1 = "abcd", str2 = "abcd", str3; System.out.println(str1.equals(str2)); System.out.println(str1.length()); System.out.println(str1.charAt(1)); System.out.println(str1.compareTo("aBcE")); System.out.println(str1.compareTo("aBcC")); System.out.println(str1.compareTo("aBcD")); System.out.println(str1.indexOf('D')); System.out.println(str1.indexOf("Bc")); System.out.println(str1.indexOf("zz")); // parts cut out here StringTest.java // StringTest.java - demo some String methods public class StringTest { public static void main(string[] args) { String str1 = "abcd", str2 = "abcd", str3; // parts cut out here System.out.println(str1.concat("efg")); str3 = str1.tolowercase(); System.out.println(str3); str3 = str1.touppercase(); System.out.println(str3); System.out.println(str1); str3 = String.valueOf(123); System.out.println(str3.equals("123"));

String Literals String literals are instances of String Therefore, we can invoke instance methods on them "abc".length() "hello".charat( 1 ); String is unusual Because strings are so common, Java provides some special syntax for the class String special support for concatenation special support for String literals String is the only class that is treated specially String Concatenation The '+' operator is overloaded to support String concatenation "hello " + "world" is equivalent to "hello ".concat( "world" ); String Literals String literals are supported String s = "hello"; is equivalent to char[] temp={ h, e, l, l, o ; String s = new String(temp); Instance methods are operations on objects

Strings are immutable Instances of class String are immutable Once its value is assigned, it cannot be changed We can create a new string, but we can't change the one we have. One implication of this is that when we pass a String to a method String s = "hello"; somemethod( s ); StringBuffer StringBuffer is another standard Java class for representing strings It has instance methods that allow you to change the value of a StringBuffer object These are called mutator methods insert(), reverse(), replace(), setcharat(), deletecharat(),... we know that its value will be unchanged when the method returns s will have the value "hello" when somemethod returns StringBufferTest.java // StringBufferTest.java - demo StringBuffer methods public class StringBufferTest { public static void main(string[] args) { StringBuffer sbuf1 = new StringBuffer(); StringBuffer sbuf2 = new StringBuffer("abcd"); StringBuffer sbuf3 = new StringBuffer(30); System.out.println(sbuf1.length()); System.out.println(sbuf2.length()); System.out.println(sbuf3.length()); System.out.println(sbuf1.capacity()); System.out.println(sbuf2.capacity()); System.out.println(sbuf3.capacity()); System.out.println(sbuf2.charAt(1)); // parts cut out here StringBufferTest.java // StringBufferTest.java - demo StringBuffer methods public class StringBufferTest { public static void main(string[] args) { sbuf2.setcharat(2,'z'); System.out.println(sbuf2); sbuf2.append("xyz"); System.out.println(sbuf2); sbuf2.append('?'); sbuf2.insert(4, "---"); sbuf2.insert(2, '+'); System.out.println(sbuf2); sbuf2.reverse(); System.out.println(sbuf2); System.out.println("sbuf2 capacity " + sbuf2.capacity()); System.out.println("sbuf2 length " + sbuf2.length());

Object Declarations When you declare an object, you are really creating a reference Similar to array declaration and allocation StringBuffer sbuf1 = new StringBuffer(); StringBuffer sbuf2 = new StringBuffer("abcd"); StringBuffer sbuf3 = new StringBuffer(30); Can also do this with separate statements StringBuffer sbuf1; sbuf1 = new StringBuffer(); Elements of a Simple Class As discussed earlier, a class describes the data values that make up an object along with the operations that can be applied to the object The data values are stored in instance variables, which are also known as fields or data members. The operations are described by instance methods, which are sometimes called procedure members. Example: Counter We often want to count things, why not create an abstraction for doing it? Advantage: you can reuse it in different places in the program, or even in other programs Data: Current value of the counter (initially zero) Operations: Reset, Increment, Decrement, Get the current value CounterTest.java class CounterTest { public static void main( String[] args ) { Counter countthis = new Counter(); Counter countthat = new Counter(); countthis.increment(); countthis.increment(); countthat.increment(); System.out.println("countThis: " + countthis.get() ); System.out.println("countThat: " + countthat.get() );

class Counter { int value; Counter.java Objects in Memory void reset() { value = 0; void increment() { value++; void decrement() { value--; int get() { return value; No main() method value is an instance variable Instance methods no static keyword CountThis CountThat Local variables in main() Counter objects value 2 value 1 Class Counter reset() increment() decrement() get() Important Details Each Counter object has its own copy of the member variables In this case, the integer variable called value When the methods are called, the call is of the form <objectname>.<methodname>() The object itself is an implicit parameter to the method, so that any references to the data access that object s copy of the instance variables Abstract Data Type Counter is an example of an Abstract Data Type (ADT) an abstraction representing a particular type of data Classes allow us to implement ADTs The data and methods combine to implement the functionality we desire or expect for this type of data The implementation details are hidden from the user The implementation is all in one place The type can be used in many different places in the program or in many programs

Package In general, each class is in a separate file The name of the file should match the class name (with.java at the end) All classes in the same directory are part of the same package Whether or not a method is in the same class or package as the data or method it is accessing affects what it can see and do. Data Hiding It is desirable to hide the inner details of a class (ADT) from the users of the class We want to be able to determine the correctness of our class without having to examine the entire program that it is used in For example, with our Counter class, we want to ensure that the value doesn't change by more than 1. Data Hiding Accessing instance variables from outside the class violates the data hiding principle class CounterTest2 { public static void main( String[] args ) { Counter c = new Counter(); c.value = 150; System.out.println( "c.value = " + c.get() ); A Better Counter Class Use the private and public access specifiers to control access to instance variables and methods class Counter { private int value; public void reset() { value = 0; public void increment() { value++; public void decrement() { value--; public int get() { return value;

Public/Private/Default private methods/fields cannot be accessed from outside of the class public methods/fields can be accessed from anywhere default (no specifier) methods/fields have package access they can be accessed from other classes in the same package if you don't specify a package (see section 12.11), all classes in the same directory are part of the same default, un-named package