Week 7 - More Java! this stands for the calling object:

Similar documents
Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

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

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Expanded Guidelines on Programming Style and Documentation

Full file at

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.

CST141 Thinking in Objects Page 1

More About Objects and Methods

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

Chapter 4 Defining Classes I

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Fall 2017 CISC124 9/16/2017

Introduction to Programming Using Java (98-388)

Chapter 6 Introduction to Defining Classes

Supplement D: Expanded Guidelines on Programming Style and Documentation

EECS168 Exam 3 Review

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

Classes, interfaces, & documentation. Review of basic building blocks

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

Lesson 3: Accepting User Input and Using Different Methods for Output

Pace University. Fundamental Concepts of CS121 1

Defining Classes and Methods

Defining Classes and Methods

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

CS Exam 1 Review Suggestions

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

A JavaBean is a class file that stores Java code for a JSP

CT 229 Fundamentals of Java Syntax

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

CHAPTER 7 OBJECTS AND CLASSES

Oct Decision Structures cont d

Lecture 2 Tao Wang 1

Java Programming Style Guide

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

CPS122 Lecture: Defining a Class

CS112 Lecture: Defining Instantiable Classes

Week 6: Review. Java is Case Sensitive

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

JAVA: A Primer. By: Amrita Rajagopal

PROGRAMMING FUNDAMENTALS

Documentation Requirements Computer Science 2334 Spring 2016

Key Differences Between Python and Java

6.170 Laboratory in Software Engineering Java Style Guide. Overview. Descriptive names. Consistent indentation and spacing. Page 1 of 5.

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

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

Java Style Guide. 1.0 General. 2.0 Visual Layout. Dr Caffeine

Assignment Marking Criteria

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

CSE 142 Su 04 Computer Programming 1 - Java. Objects

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

Defining Classes and Methods

Text User Interfaces. Keyboard IO plus

9 Working with the Java Class Library

1B1b Classes in Java Part I

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Dot and Scope Resolution Operator

5. Defining Classes and Methods

Midterms Save the Dates!

5. Defining Classes and Methods

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Initial Coding Guidelines

Software Design and Analysis for Engineers

CSE 11 Style Guidelines

JAVA GUI PROGRAMMING REVISION TOUR III

CS 11 java track: lecture 3

Creating Classes and Objects

Chapter Two Bonus Lesson: JavaDoc

CSCI 2101 Java Style Guide

CS121/IS223. Object Reference Variables. Dr Olly Gotel

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

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Fall 2017 CISC124 9/27/2017

Computational Expression

CHAPTER 7 OBJECTS AND CLASSES

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

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

4 Programming Fundamentals. Introduction to Programming 1 1

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference

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

Language Features. 1. The primitive types int, double, and boolean are part of the AP

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

Chapter 5. Defining Classes II. Slides prepared by Rose Williams, Binghamton University

User Interface Programming OOP/Java Primer. Step 3 - documentation

THE CATHOLIC UNIVERSITY OF EASTERN AFRICA A. M. E. C. E. A

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

5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!

Write for your audience

Final Exam Practice. Partial credit will be awarded.

Introduction to the course and basic programming concepts

Midterms Save the Dates!

What is an algorithm?

Full file at

Chapter 1 Introduction to Java

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

Transcription:

Week 7 - More Java! Variable Scoping, Revisited this Parameter Encapsulation & Principles of Information Hiding: Use of public and private within class API, ADT javadoc Variables of class Type Wrapper classes Libraries/Packs Coding Style Variable Scoping, Revisited public class testing { // Instance variables or attributes // are known everywhere within the class private String name; private int ; // Static attributes or class variables // are also known everywhere within the // class. public static final RETIREMENT_AGE = 65; // Method parameters are local to method. public boolean retired_yet (int input_age) { // Variables declared inside method are local // to method. boolean check_result; if (input_age < 1) { // Variables declared inside a block are // local to the block but cannot be // used elsewhere in the method. boolean try_again = ; // Variables declared within for loop // are local to loop. for (int i=1; i < 100, i++) { // statements // end for // end if // end method retired_yet // end testing class APSC142 - Prof.McLeod 1 APSC142 - Prof.McLeod 2 Variable Scoping, Revisited Design for efficient use of memory - Minimize number of instance variables. Better to not declare variables inside blocks or within for loop statement. This kind of scoping is not handled the same for different Java compilers. Don t declare variables within loops. Java *does not* have global variables. Global variables would be declared at the same level as the class definition, and would be known to all classes this Parameter this stands for the calling object: public class testing { private String name; private int ; public void set_age() { this. = SavitchIn.readLineInt(); Public void set_name() { this.name = SavitchIn.readLine(); public testing () { this.set_age(); this.set_name(); // end class testing APSC142 - Prof.McLeod 3 APSC142 - Prof.McLeod 4 1

this Parameter, Cont. The use of this is optional. This code is equivalent to the that on the previous slide. If a calling object is not specified, then this. is assumed by the compiler. public class testing { private String name; private int ; public void set_age() { = SavitchIn.readLineInt(); Public void set_name() { name = SavitchIn.readLine(); public testing () { set_age(); set_name(); // end class testing Encapsulation & Information Hiding The detail of what goes on in a class - the instance variables and methods - whether they are private or public, is called the implementation of the class. Good encapsulation means that the implementation of the class is hidden from the user. The user who wants to use the class can only see the interface provided by the programmer of the class. The interface includes a description of the public methods and constants, including what they do, how to call them and what they return. The interface is also called the API or Application Programmer Interface. The term ADT or Abstract Data Type, in Java, refers to a well-encapsulated class. APSC142 - Prof.McLeod 5 APSC142 - Prof.McLeod 6 Guidelines for Good Encapsulation 1. Place a comment before a class definition that describes an overall view of what the class does. It should also include the author s name, creation date, last modification date, and possibly a version number. 2. All instance variables should be private. 3. Provide public accessor and mutator methods. 4. Provide all public methods necessary to perform the function of the class, in terms of how it manipulates its data. 5. Place a comment before each public method, specifying what it does and how it is used. 6. Make any helping methods private. Documentation with Javadoc Java is supplied with a utility program called javadoc.exe. javadoc strips comments that use a certain format, from a file and produces documentation in html format. javadoc extracts information for every item listed, provided you have put in the appropriate comments: pack public class public interface public method public instance variable public constant Very useful utility for documenting code under construction. APSC142 - Prof.McLeod 7 APSC142 - Prof.McLeod 8 2

Documentation with Javadoc, Cont. Comments are formatted as below: /** * Summary sentence or phrase. * More general information about the * program, class, method or variable which * follows the comment, using as many lines * as necessary. * * zero or more tags to specify more specific * kinds of information, such as parameters * and return values for a method */ javadoc tags for class descriptions include @version and @author. Method descriptions would use @param and @return tags. Variable descriptions would have a comment like the one above, just before the variable declaration. Text in a javadoc comment can also contain normal HTML tags, so text can be bolded, italicized, etc. Documentation with Javadoc, Cont. Example of a class comment: /** * A class for formatting numbers. * Double or float type numbers are formatted * to contain a user-defined number of digits * after the decimal point. * * @version 1.01 25 February, 2001 * @author Alan McLeod */ A method comment: /** * Formats a double into a string. * * @param x the number to format * @return the formatted string */ APSC142 - Prof.McLeod 9 APSC142 - Prof.McLeod 10 Documentation with Javadoc, Cont. javadoc.exe is a DOS-program that should be run in a DOS window. The program is in the JBuilder2\java\bin directory. Type javadoc at the DOS prompt to get a listing of optional command line parameters. What you get when you run javadoc with SavitchIn.java, for example: A simple class: Variables of class Type public class Student { private int ; private boolean ; private boolean ; public Student (int n, boolean awake, boolean paper) { set_student(n, awake, paper); // end default constructor public void set_student (int n, boolean awake, boolean paper) { = n; = awake; = paper; // end set_student method // more methods // end Student class APSC142 - Prof.McLeod 11 APSC142 - Prof.McLeod 12 3

Creating a new instance of the student class: Student = new Student (18,, ); Is really the same as: In memory just after creation of : Variable Name null Student ; // Creates variable // of class type. = new Student (18,, ); The first statement creates a memory location to be associated with the variable. The second statement links memory locations for all attributes and methods to the above memory location, and then calls the constructor method which assigns values to the attributes. APSC142 - Prof.McLeod 13 APSC142 - Prof.McLeod 14 In memory just after new : In memory just after constructor: null 18 null null APSC142 - Prof.McLeod 15 APSC142 - Prof.McLeod 16 4

Suppose we create another instance of Student, called artsstudent: Suppose we used: artsstudent = ; artsstudent artsstudent 18 18 APSC142 - Prof.McLeod 17 APSC142 - Prof.McLeod 18 Suppose we used: artsstudent.set_student(32,, ); What would be returned by:.get_age(); artsstudent artsstudent 32 32 APSC142 - Prof.McLeod 19 APSC142 - Prof.McLeod 20 5

What would be returned by: == artsstudent; What would be returned by: == artsstudent; artsstudent 32 When the equality operator is used to compare objects, it only compares the memory locations of the two objects. Same thing when comparing two variables of String type. Should define an equals method as member of Student class. APSC142 - Prof.McLeod 21 APSC142 - Prof.McLeod Add equals method to Student class: public boolean equals (Student otherstudent) { return (( == otherstudent.get_age()) && ( == otherstudent.get_awake()) && ( == otherstudent.get_paper())); // end method equals Now.equals(artsStudent) will return. Note that Java has a "loophole". In the code it would be more efficient to use "otherstudent.", etc. Java will allow me to do this! Even though is private! This can only work because the "equals" method is in the Student class. Note that only a memory address is passed into a method when a class type variable is used as a parameter. This is called parameter passing by reference. This also means that the passed object s attributes can be changed by the method. Primitive types are passed by value. The method cannot change the value of the variable used as an argument to the method. Don t confuse class variables (static attributes) with variables of the class type! APSC142 - Prof.McLeod 23 APSC142 - Prof.McLeod 24 6

Wrapper Classes Each primitive type has an associated wrapper class: char int long float double Character Integer Long Float Double Each wrapper class object can hold the value that would normally be contained in the primitive type variable, but now has a number of useful static methods. Wrapper Classes, Cont. Some Character class static methods: Character letter = new Character( L ); Character.toUpperCase( l ) // returns L Character.toLowerCase( L ) // returns l Character.isUpperCase( l ) // returns Character.isLowerCase( l ) // returns Character.isLetter( 3 ) // returns Character.isDigit( 4 ) // returns Character.getNumeric( A ) // returns 65 letter.equals( A ) // returns char aletter = letter.char(); APSC142 - Prof.McLeod 25 APSC142 - Prof.McLeod 26 Wrapper Classes, Cont. Some Integer class static methods: Integer number = new Integer(46); Integer num = new Integer( 908 ); Integer.MAX_VALUE // gives maximum integer Integer.MIN_VALUE // gives minimum integer Integer.parseInt( 453 ) // returns 453 Integer.toString(653) // returns 653 number.equals(num) // returns int anumber = number.int(); Wrapper Classes, Cont. Some Double class static methods: Double a = new Double(4.5e-3); Double an = new Double( 0.0056 ); Double.MAX_VALUE // maximum positive double Double.MIN_VALUE // minimum positive double Double.toString(aVal) if 1e-3 < aval < 1e7 then returns ###.###, else aval is returned as #.###e##. There is always a minimum of one digit after the decimal point. The number of digits is the minimum needed to uniquely distinguish the argument value from adjacent values of type double. a.equals(an) // returns Note that double values much match exact bit patterns. double anum = a.double(); APSC142 - Prof.McLeod 27 APSC142 - Prof.McLeod 28 7

Libraries or Packs A pack is a collection of classes that are grouped together under one pack name. The classes are still in separate files and follow the same naming rules, as always. The first line in a class that is to be included in a pack must be: pack pack_name; pack_name must include the directory path from that given by the CLASSPATH DOS environmental variable (internal to JBuilder2). For example, if your pack classes are in C:\JBuilder2\myclasses\myStuff\utilities then pack_name would be mystuff.utilities. In order to use all these classes a program uses an import statement: import mystuff.utilities.*; Libraries or Packs, Cont. The import statement must also be right at the top of the program, before the class definition line. The * at the end tells the import statement to import all classes - otherwise you can specify which classes you want to import. Packs that are often imported for simple input/output (screen or file) are java.io.* and java.util.*. GUI tools are available from Swing: javax.swing.* and/or AWT: java.awt.* and java.awt.event.*. Essentially, importing packs allows you to extend the Java langu with the tools that you need for your purposes. APSC142 - Prof.McLeod 29 APSC142 - Prof.McLeod 30 Coding Style Guidelines The purpose of adding white space and comments to your code is to make it easier to maintain, as well as making it more easily understood by another programmer. Properly formatted comments can also be used to generate external documentation (using javadoc ). But don t go overboard! Too many comments swamp out the code. Don t repeat yourself in comments! Be concise! Use descriptive variable names, that might use one, two or possibly even three words - don t use a sentence! For example: num_students is much better than: variable_to_keep_track_of_the_number_of_students Coding Style Guidelines, Cont. 1. s Use descriptive variable names (method names will probably contain a verb). Use all uppercase for constants. Primitive type variable names start with a lowercase letter, object names start with an upper case letter. Use _ to space out the variable name. 2. Indentation Use a three-space indent (JBuilder default). Indent code in any block. Line up braces ({) as follows: while (total < 25) { total += 5; System.out.println("The total is " + total); Line up else with corresponding if: if (num_students > 100) statement; else statement; APSC142 - Prof.McLeod 31 APSC142 - Prof.McLeod 32 8

Coding Style Guidelines, Cont. 3. Spacing Put one space after every comma in a parameter list. Put one space on either side of a binary operator (like: +, -, <, >=, etc.) Do not put a space after ( or before ). Do not put a space before ;. Put one space before (. Do not put a space before [ 4. Comments Add comments as you complete logical units of your code - don t wait until you are finished. Assume that your reader is familiar with the Java langu, but has no idea of how your program works. Make sure your comments keep up with code changes. If you use a block comment (/*.*/) then add a * to the left of each line. Comment any variable name that is not completely self-explanatory. Coding Style Guidelines, Cont. 4. Comments, Cont. A comment should be aligned with the block it is describing. Block comments should be used to describe each class and method. Include author name(s), and date, version or revision number (for larger projects) in the comment describing a class. It should also describe the purpose of the class. Method comments should include a description of what the method does, and the algorithm used. The main method comment should describe the overall purpose of the main method and what input & output should be provided and expected. Add short comments to the code body of a method where appropriate. Provide a brief explanation of logical units of code. When you are coding, you can add comments to remind yourself of an area that will need additional work after another module is completed, for example. Add an in-line comment after each close to indicate what they close. APSC142 - Prof.McLeod 33 APSC142 - Prof.McLeod 34 Coding Style Guidelines, Cont. 5. External Documentation At present, you append the sample DOS output of your program to the end of your program as a comment. That is all that is required for this course. External documentation is supplied for a user of your code. It is less technical and more descriptive. It describes the purpose of the program and describes the user interface (but not the implementation!). The description would include the input and output of the program, and the meanings of various error messs, etc. You must assume that your user knows nothing about programming, and has only fundamental computer skills. APSC142 - Prof.McLeod 35 9