Chapter 4 Defining Classes I

Similar documents
Chapter 4. Defining Classes I

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

EECS168 Exam 3 Review

Chapter 6 Introduction to Defining Classes

Chapter 4. Defining Classes I

Introduction to Programming Using Java (98-388)

Defining Classes and Methods

Methods and Data (Savitch, Chapter 5)

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Defining Classes and Methods

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Equality for Abstract Data Types

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

Methods. Methods. Mysteries Revealed

Object Oriented Programming in C#

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

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

Defining Classes and Methods

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

CS112 Lecture: Defining Instantiable Classes

5. Defining Classes and Methods

Absolute C++ Walter Savitch

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Anatomy of a Class Encapsulation Anatomy of a Method

Programming II (CS300)

Programming II (CS300)

CSI33 Data Structures

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

ECE 122. Engineering Problem Solving with Java

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Chapter 4: Writing Classes

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

Assertions, pre/postconditions

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

CS 231 Data Structures and Algorithms, Fall 2016

Defining Classes and Methods

A A B U n i v e r s i t y

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

CS313D: ADVANCED PROGRAMMING LANGUAGE

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

And Even More and More C++ Fundamentals of Computer Science

CS110D: PROGRAMMING LANGUAGE I

Objects and Classes -- Introduction

Java Object Oriented Design. CSC207 Fall 2014

Handout 7. Defining Classes part 1. Instance variables and instance methods.

COP 3330 Final Exam Review

C++ (Non for C Programmer) (BT307) 40 Hours

JAVA GUI PROGRAMMING REVISION TOUR III

More About Objects and Methods

More About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

Lesson 10B Class Design. By John B. Owen All rights reserved 2011, revised 2014

Data Structures (list, dictionary, tuples, sets, strings)

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

Problem Solving with C++

UNDERSTANDING CLASS DEFINITIONS CITS1001

APCS Semester #1 Final Exam Practice Problems

CMSC131. Library Classes

Declarations and Access Control SCJP tips

CS-202 Introduction to Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Cpt S 122 Data Structures. Introduction to C++ Part II

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Recitation 02/02/07 Defining Classes and Methods. Chapter 4

C++ Important Questions with Answers

Objects as a programming concept

CHAPTER 7 OBJECTS AND CLASSES

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000

CompuScholar, Inc. 9th - 12th grades

Java Primer 1: Types, Classes and Operators

HST 952. Computing for Biomedical Scientists Lecture 5

Lecture 5: Methods CS2301

Java and OOP. Part 2 Classes and objects

Intermediate Programming & Design (C++) Classes in C++

CS162: Introduction to Computer Science II

Principles of Object Oriented Programming. Lecture 4

Computer Programming C++ Classes and Objects 6 th Lecture

Inheritance and Polymorphism

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

Pace University. Fundamental Concepts of CS121 1

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

CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations

Lecture 7. Log into Linux New documents posted to course webpage

Transcription:

Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the two components of classes. With the introduction of methods, we can discuss parameters and parameter passing. Encapsulation is then introduced with the designation of accessor and mutator methods. Then, the concept of method overloading is introduced. Constructors are given coverage in the last section of this chapter. KEY TERMS Object call-by-value private Method parameters as local variables accessor method, Instance formal parameter mutator method Member actual parameter precondition Field this parameter postcondition instance variable mask a variable overloading New equals method signature Heading tostring constructor method body println used with objects constructor arguments Invocation + used with objects resetting object values Body recursive method no-argument constructor return statement driver program default constructor return in a void method bottom-up testing import local variable stub tokens Block information hiding nexttoken compound statement abstraction hasmoretokens Parameter encapsulation, choosing delimiters Argument public

4.1 CLASS DEFINITIONS Instance Variables and Methods More about Methods Local Variables Blocks Parameters of a Primitive Type Simple Cases with Class Parameters The this Parameter Methods that Return a Boolean Value The Methods equals and tostring Recursive Methods 4.3 OVERLOADING Rules for Overloading CHAPTER OUTLINE 4.2 INFORMATION HIDING AND ENCAPSULATION public and private Modifiers Accessor and Mutator Methods Preconditions and Postconditions 4.4 CONSTRUCTORS Constructor Definitions Default Variable Initializations An Alternative Way to Initialize Instance Variables The StringTokenizer Class Key Points A Class is a Type The notion of the difference between a class and an instance comes up again in this chapter. Also, students need to be made aware that you can create a variable whose value will be an object. The type of the variable will be the class. The new Operator The new operator is what is used to actually create an instance. You would use the new operator when you are assigning a value to a variable whose type is a class. Class Definition A class definition begins with the keywords public class followed by the name of the class. The definition of the class is enclosed between {} and usually the instance variables for a class are listed before the methods. This is by convention and not compiler enforced. Normally, all the instance variables are placed at the top of the file. File Names and Locations In java, each file should contain one class and the name of the class and the file will be the same. For now, all files for the same project should be in the same directory. There are other ways to organize files, namely into packages, but the text has not introduced this idea yet. return Statements When writing a method that has a return type that is other than void, a return statement needs to be in the method. If omitted, this will cause a compiler error. A void method does not need a return statement. Method Definitions The first part of a method definition is the method signature, which consists of its visibility, which is usually public, its return type, the method name and the parenthesized list of parameters. Methods are first introduced where they do not take any parameters. The method body is enclosed in {} and if the return type of a method is other than void, a return statement must be included in the list of statements for the method.

Local Variables You can have instance variables that are accessible to the entire class. You can also create variables inside a method that are only accessible within that method. With these variables, you do not need to give them a visibility, just a type and a name. You can then use these variables in any computation within the method. Global Variables This type of variable in not available in Java. Blocks The notion of blocks of code encompasses the idea that code enclosed in {} is considered a block. This can be the {} around a loop body or within an if-else statement. However, for purposes of local variables, they are only accessible from within the block, but their names cannot be repeated within the method. Parameters of a Primitive Type Parameters into a method can be of a primitive type. When primitive values are passed into a method, the value of the parameter is initialized to the value that is passed in from the method call. This method is call-by-value parameter passing and unlike other languages, is the only type of parameter passing that Java supports for primitive types. You can also pass in parameters whose type is a class. These parameters are handled by Java differently and will be discussed in the next chapter. main is a void Method. If you look at the method signature of the main method, you will see that its return type is void. It also takes a parameter named args. We will discuss static and the type of thing that the parameter is (an array) in later chapters. The this Parameter. There is a keyword in Java whose meaning is to refer to the class itself. The keyword this is used whenever you want to refer to the class. You can use the keyword this as a calling object for methods within the same class. We will see using this as a parameter when we talk about passing objects as parameters. The Methods equals and tostring. It is good practice when writing Java classes that you write an equals and a tostring method. The equals method can help determine whether two objects are equal and returns a Boolean value. The tostring method returns a String representation of an object. The Fundamental Rule for Testing Methods When testing a new method, it should be maintained that all of the other methods being called in the testing program have already been tested and debugged. Encapsulation The idea of encapsulation is that all of the data and the actions that can be performed are combined in one place (class). If a class is well designed, the user of the class only needs to be told what the class is capable of, not the specific details of how it is implemented. API The Application Programmer Interface is used to tell users of the class what the class can do. There is an online Java API that is available for all of the classes inside Java. ADT Abstract Data Types are written using information hiding techniques. Signature The signature of the method consists of its visibility, return type, method name, and parameter list. This term can also be introduced right when methods are first introduced in the text. Overloading Java supports method overloading. Two methods can have the same name if they differ in number and or type of parameters.

You Cannot Overload Operators in Java Unlike other languages, Java does not provide the ability to overload operators. Constructor The constructor is a special method that is in charge of setting up the initial state of an object. It is executed when an object is created using the keyword new. Is a Constructor Really a Method? A constructor does not follow the same signature as other methods (no return type) and it is not called in the same manner. Tips Any Method Can Be Used as a void Method. This tip points out the fact that if the return value from a method is not placed into a variable, the value is essentially lost. This could be a positive for a program in that we can ignore a value that is returned if we do not need it. Declaring Variables in a for Statement In a for statement, the first part is an initialization, commonly seen as int n = value. However, when the variable n is declared in the for loop, it is not accessible outside of the loop. To avoid this problem, we must declare the variable outside of the loop and only initialize it in the loop. This feature of when variables can be accessed can be both a pitfall and a help depending on when the variable needs to be accessed. Testing Methods Each method of a class should be tested. One of the easiest and best ways to do this is to create a driver class that creates an instance of the object and tests each method in turn. Care needs to be taken when testing methods that call other methods so that it is assured that all methods are working properly. A Class has Access to private Members of All Objects of the Class When an entity is declared private the only elements that have access to it are other entities inside that same class. This is the most restrictive visibility. Mutator Methods Can Return a Boolean Value An alternative implementation for a mutator method is to have the method return a boolean value that indicates whether the changes requested by the caller were successful. You Can Invoke Another Method in a Constructor You can make a call to another method from the constructor by simply using the same technique as we have used to call methods previously. Include a No-Argument Constructor. If you do not provide a constructor for a class, Java provides one for you that takes no arguments. It is a good idea to include a no-arg constructor that does something meaningful so that the default constructor that does nothing will not be called. You lose the default no-arg constructor as soon as there is at least one constructor defined in the class, so having another that takes no parameters is a good programming practice. Pitfalls Use of the Terms Parameter and Argument The use of these two terms varies from author to author and it should be well known which context the words are used in. For this text, parameter is used to describe the formal parameter or the name of the parameter in the method signature. The word argument is used to describe the actual parameter or the actual value that is passed into the method when it is called.

Overloading and Automatic Type Conversion When a method is called in Java, it looks to match the method signature. If it fails to match the signature exactly, Java will try to do a conversion to match. For example, it may convert an int into a double to match for a signature. This has the potential to cause problems within a program. You Cannot Overload Based on the Type Returned A method can not be overloaded based on the return type of the method. Overloading is only concerned with the parameters for a method, not the return types.