Chapter 3 Implementing Classes

Similar documents
D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

An Introduction to Classes

Inheritance, overloading and overriding

Chapter 13 - Inheritance

D06 PROGRAMMING with JAVA

ICOM 4015: Advanced Programming

Moving from CS 61A Scheme to CS 61B Java

Lecture 5: Java Fundamentals III

CSE 308. Coding Conventions. Reference

Java: overview by example

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Java CPD (I) Frans Coenen Department of Computer Science

CS 111 Classes I 1. Software Organization View to this point:

Object Oriented Programming Design Basics CMSC 202

Computer Programming C++ Classes and Objects 15 th Lecture

D06 PROGRAMMING with JAVA

CSC 221: Computer Programming I. Fall 2006

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

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Computer Programming I

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

D06 PROGRAMMING with JAVA

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Chapter 1 Java Program Design and Development

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Lecture J - Exceptions

Chapter 3. Input and output. 3.1 The System class

It has a parameter list Account(String n, double b) in the creation of an instance of this class.

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

LAB4 Making Classes and Objects

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

AP Computer Science Java Subset

Java Basics: Data Types, Variables, and Loops

Java Classes. GEEN163 Introduction to Computer Programming

Basic Object-Oriented Programming in Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

CS193j, Stanford Handout #10 OOP 3

Contents. 9-1 Copyright (c) N. Afshartous

CISC 181 Project 3 Designing Classes for Bank Accounts

CMSC 202H. ArrayList, Multidimensional Arrays

Understanding class definitions

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Introduction to Java Lecture Notes. Ryan Dougherty

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

public void creditaccount(string accountnumber, float amount) { this.accounts.get(accountnumber).credit(amount); }

6.1. Example: A Tip Calculator 6-1

C++ INTERVIEW QUESTIONS

Install Java Development Kit (JDK) 1.8

Mutual Exclusion using Monitors

Introduction to Object-Oriented Programming

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

D06 PROGRAMMING with JAVA

Object Oriented Software Design II

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

C Compiler Targeting the Java Virtual Machine

13 Classes & Objects with Constructors/Destructors

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Programming Languages CIS 443

Java Interview Questions and Answers

Basic Java Syntax. Program Structure

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Introduction to Java. CS 3: Computer Programming in Java

CS170 Lab 11 Abstract Data Types & Objects

Some Scanner Class Methods

More on Objects and Classes

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Using Files as Input/Output in Java 5.0 Applications

Java Application Developer Certificate Program Competencies

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Object-Oriented Programming in Java

WRITING DATA TO A BINARY FILE

C# and Other Languages

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

ADT Implementation in Java

Coding Standard for Java

UML Class Diagrams. Lesson Objectives

Introduction to Programming

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Fundamentals of Java Programming

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Software Development (CS2500)

CS 106 Introduction to Computer Science I

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

Chapter 2: Elements of Java

Remote Method Invocation

Lab Experience 17. Programming Language Translation

AP Computer Science Java Mr. Clausen Program 9A, 9B

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Programming to Interfaces

Ch 7-1. Object-Oriented Programming and Classes

Introduction to Object-Oriented Programming

Transcription:

Chapter Goals Chapter 3 Implementing Classes To become familiar with the process of implementing classes To be able to implement simple methods To understand the purpose and use of constructors To understand how to access instance fields and local variables To appreciate the importance of documentation comments A black box is something that performs a task, but hides how it does it This is also called encapsulation Black boxes in a car: transmission, electronic control module, etc Black Box Levels of abstraction: Software Design Old times: computer programs only manipulated primitive types such as numbers and characters Gradually programs became more complex, vastly increasing the amount of detail a programmer had to remember and maintain 3.2 Designing the Public Interface to a Class Your task: Develop a BankAccount class First step: Define essential features Behavior of bank account (abstraction): deposit money withdraw money get balance 1

Designing #1: Methods Methods of BankAccount class: deposit withdraw getbalance Support method calls such as the following: harryschecking.deposit(2000); harryschecking.withdraw(500); System.out.println(harrysChecking.getBalance()); ()); Which methods are accessors? Mutators? Designing: Method Definitions COMPONENTS: access specifier (Ex. public) return type (Ex. String or void) method name (Ex. deposit) list of parameters (Ex. amount for deposit) method body in braces Syntax 3.1: Method Definition Examples: public void deposit(double amount)... public void withdraw(double amount)... public double getbalance()... accessspecifier returntype methodname(parametertype parametername,...) method body Example: public void deposit(double amount) Purpose: To define the behavior of a method Designing #2: Constructor A constructor initializes the instance variables Constructor name = class name public BankAccount() Constructors Constructor body is executed when new object is created Statements in constructor body will set the internal data of the object that is being constructed How does the compile know which constructor to call? 2

Constructor vs. Method Constructors are a specialization of methods Goal: to set the internal data of the object 2 differences All constructors are named after the class Therefore all constructors of a class have the same name No return type listed EVER! Syntax 3.2 : Constructor Definition accessspecifier ClassName(parameterType parametername,, ) constructor body Example: public BankAccount(double initialbalance) Purpose: To define the behavior of a constructor BankAccount Public Interface The public constructors and methods of a class form the public interface of the class. public class BankAccount // private fields-- // Constructors public BankAccount() public BankAccount(double initialbalance) ) // Methods public void deposit(double amount) public void withdraw(double amount) public double getbalance() Remember Public methods and constructors provide the public interface to a class They are how you interact with the black box Our class is simple, but we can do many things with it Notice we haven t t defined the method body yet, but know how we can use it 3.3 Commenting the Public Interface Part of creating a well-defined public interface is always commenting the class and methods behaviors The HTML pages from the API are created from special comments in your program called javadoc comments Place before the class or method.. 3

Javadoc Comments Begin with Ends with Put * on lines in between as convention, makes it easier to read Javadoc tags - @ mark is one @author, @param@ param,, @return Benefits Online documentation (Assignment 1) Other java documents Javadoc comments First sentence is extracted for HTML page Carefully explain method @param for each parameter Omit if no parameters @return for the value returned Omit if return type void * Withdraws money from the bank account. * @param@ the amount to withdraw public void withdraw(double amount) // implementation filled in later * Gets the current balance of the bank * account. * @return the current balance public double getbalance() // implementation filled in later Class Comment A bank account has a balance that can be changed by deposits and withdrawals. public class BankAccount 3.4 Instance Fields Remember: methods are the public interface of a class Instance Fields are part of the internal workings - An object stores its data in instance fields Field: : a technical term for a storage location inside a block of memory Instance of a class: : an object of the class AKA Data Members The class declaration specifies the instance fields: public class BankAccount private double balance;... 4

An instance field declaration consists of the following parts: access specifier (usually private) type of variable (such as double) name of variable (such as balance) Each object of a class has its own set of instance fields You should declare all instance fields as private Access Specifiers Access Specifiers defines the accessibility of the instance field and methods private only accessible within the class methods public accessible in outside class methods and inside class methods Private enforces encapsulation/black box AKA Visibility Modifier Syntax 3.4 : Instance Field Declaration accessspecifier class ClassName accessspecifier fieldtype fieldname; Example: public class BankAccount private double balance; Purpose: To define a field that is present in every object of a class Accessing Instance Fields The deposit method of the BankAccount class can access the private instance field: public void deposit(double amount) double newbalance = balance + amount; balance = newbalance; Other methods cannot: public class BankRobber public static void main(string[] args) BankAccount momssavings = new BankAccount(1000); momssavings.balance = -1000; // ERROR Encapsulation = Hiding data and providing access through methods By making data members private, we hide internal workings of a class from a user Note: We can have public instance fields and private methods, but commonly we do not 5

3.5 Implementing Constructors & Methods Constructors contain instructions to initialize the instance fields of an object public BankAccount() balance = 0; public BankAccount(double initialbalance) balance = initialbalance; Constructor Call Example BankAccount harryschecking = new BankAccount(1000); Create a new object of type BankAccount Call the second constructor (since a construction parameter is supplied) Set the parameter variable initialbalance to 1000 Set the balance instance field of the newly created object to initialbalance Return an object reference, that is, the memory location of the object, as the value of the new expression Store that object reference in the harryschecking variable Why put instructions in a method? or why not just have one long list of instructions in our programs? 1. smaller easier 2. test & debug once, execute as often as needed 3. more readable code Implementing Methods Some methods do not return a value public void withdraw(double amount) double newbalance = balance - amount; balance = newbalance; Some methods return an output value public double getbalance() return balance; Method Call Example harryschecking.deposit(500); Set the parameter variable amount to 500 Fetch the balance field of the object whose location is stored in harryschecking Add the value of amount to balance and store the result in the variable newbalance Store the value of newbalance in the balance instance field, overwriting the old value Syntax 3.5: The return Statement return expression; or return; Example: return balance; Purpose: To specify the value that a method returns, and exit the method immediately. The return value becomes the value of the method call expression. 6

Wu s s Template Stores information about one pet. public class Pet Data member Name of the pet. private String name, kind; private int age; Constructor Initializes a new instance. * @param@ n The pet's name. public Pet( String n, String k, int a ) name = n; kind = k; age = a; Methods Returns the name of this pet. public String getname() return name; Changes the name of this pet. * @param@ newname The new name of the pet. public void changenameto( ( String newname ) // TEST THE NAME HERE name = newname; 3.6 Testing Classes Previous section was designing a class By itself, we cannot actually run a program No main() method, like most classes We create instances of it in other classes Idea: use a test class to make sure it works properly before dispensing the product 7

3.6 Testing A Class Test class: a class with a main method that contains statements to test another class. Typically carries out the following steps: Construct one or more objects of the class that is being tested Invoke one or more methods Print out one or more results Verify output is correct and program behaves as expected A Test Program. public class TestPet * Test Program starts here. * @param@ args Unused in this program. public static void main( String [] args ) // Declare and create a pet Pet pet1 = new Pet( "George", "bird", 14 ); // Test the pet's information System.out.println( ( pet1.getname() + (should be George) ); * A class to test the BankAccount class. public class BankAccountTester *Tests the methods of the BankAccount class. *@param args not used public static void main(string[] args) BankAccount harryschecking = new BankAccount(); harryschecking.deposit(2000); harryschecking.withdraw(500); System.out.println(harrysChecking.getBalance()); ()); 3.7 Categories of Variables Categories of variables Instance fields (balance in BankAccount) Local variables (newbalance( in deposit method) Parameter variables (amount in deposit method) Share the same properties of declaring and creating Differ in their lifetime (AKA( scope) Instance Field An instance field belongs to an object AKA Instance variable Each object has its own copy of the instance field The fields stay alive until no method uses the object any longer More specifically, until the object no longer exists Local Variables Local and parameter variables belong to a method You declare them and create within the method When method is done executing, variable is thrown out Every time the method is executed, a new copy of any variables is created, values do not carry over 8

Lifetime Of Variables Say we made the following method call harryschecking.deposit(500); Remember that deposit looks like this public void deposit(double amount) double newbalance = balance + amount; balance = newbalance; 3.8 Implicit and Explicit Method Parameters The implicit parameter of a method is the object on which the method is invoked Why is this important? When a method is invoked, and an instance field is used, how does it know which object it belongs to? Use of an instance field name in a method denotes the instance field of the implicit parameter the object it is called on public void withdraw(double amount) double newbalance = balance - amount; balance = newbalance; balance is the balance of the object to the left of the dot: momssavings.withdraw(500); means double newbalance = momssavings.balance - amount; momssavings.balance = newbalance; Implicit Parameters and this Every method has one implicit parameter The method knows what object called it based on a reference, but does not know/care about the identifier name E.g. you cannot say momssavings.balance in the class, because momssavings is a local variable of another class So in order to be more general, we call the implicit parameter this Exception: Static methods do not have an implicit parameter (more on Chapter 9) 9

Implicit Parameters and this double newbalance = balance + amount; // actually means double newbalance = this.balance + amount; When you refer to an instance field in a method, the compiler automatically applies it to the this parameter Example without this public class BankAccount double balance; public BankAccount(double initialbalance) balance = initialbalance; public BankAccount() balance = 0; Example with this public class BankAccount double balance; public BankAccount(double initialbalance) balance = initialbalance; public BankAccount() this(0); HOW TO 3.1 Designing and Implementing a Class Step 1: Find out what you are asked to do with an object of the class What do you want to be able to do with the object? Step 2: Specify the Public Interface Convert the list from step 1 into methods, and the parameters (think: input) they need Constructors: how do I want to initialize this object HOW-TO 3.1 (cont) Step 3: Document the public interface Create Javadoc comments for each method and the class Step 4: Determine instance fields What information needs to be maintained? HOW-TO 3.1 (cont) Go back to Step 2 if implementation doesn t t work Step 6: Test your class Step 5: Implement One at a time, from easiest to most difficult 10

Note on Style #1 A couple ways to use curly braces Option #1 public class SomeClass Option #2 public class SomeClass Note on Style #2 Book says to place instance fields at the bottom of a class public class SomeClass //constructors //methods //instance fields Most conventions have it at the top of a class public class SomeClass //instance fields //constructors //methods 11