Defining Classes and Methods

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

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

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

Defining Classes and Methods

Defining Classes and Methods

5. Defining Classes and Methods

5. Defining Classes and Methods

Defining Classes and Methods

Chapter 4 Defining Classes I

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

CHAPTER 7 OBJECTS AND CLASSES

Chapter 6 Introduction to Defining Classes

CHAPTER 7 OBJECTS AND CLASSES

Methods and Data (Savitch, Chapter 5)

Software Design and Analysis for Engineers

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

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

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.

Full file at

CS112 Lecture: Defining Instantiable Classes

Introduction to Programming Using Java (98-388)

EECS168 Exam 3 Review

Chapter 4. Defining Classes I

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Methods. Methods. Mysteries Revealed

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Anatomy of a Class Encapsulation Anatomy of a Method

STUDENT LESSON A5 Designing and Using Classes

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

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

More About Objects and Methods

by Pearson Education, Inc. All Rights Reserved. 2

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Basic Computation. Chapter 2

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Defining Classes and Methods

Chapter 4. Defining Classes I

More About Objects and Methods

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

Program Fundamentals

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

APCS Semester #1 Final Exam Practice Problems

9 Working with the Java Class Library

Computational Expression

COMP 202 Java in one week

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

CPS122 Lecture: Defining a Class

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

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

Key Differences Between Python and Java

Course Outline. Introduction to java

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


Basic Computation. Chapter 2

Section 2: Introduction to Java. Historical note

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

Software and Programming 1

Pace University. Fundamental Concepts of CS121 1

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

JAVA: A Primer. By: Amrita Rajagopal

Objects and Classes -- Introduction

Defining Classes and Methods

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Chapter. Let's explore some other fundamental programming concepts

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Inheritance. Chapter 7. Chapter 7 1

ITP 342 Mobile App Dev. Fundamentals

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

Lecture 2 Tao Wang 1

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Introduction to Classes and Objects

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

CMPT 125: Lecture 3 Data and Expressions

2 rd class Department of Programming. OOP with Java Programming

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

Java Primer 1: Types, Classes and Operators

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

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Introduction to Computers and Java

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

A Short Summary of Javali

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Logic & program control part 2: Simple selection structures

Flow of Control. Chapter 3. Chapter 3 1

Fundamental Concepts and Definitions

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

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

3 ADT Implementation in Java

egrapher Language Reference Manual

Java+- Language Reference Manual

Chapter 5: Enhancing Classes

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

Transcription:

Defining Classes and Methods Chapter 4 Chapter 4 1

Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have. It provides methods specifying the actions an object of the class can take. An object satisfying the class definition instantiates the class and is an instance of the class. Chapter 4 7

Basic Terminology, cont. The data items and the methods are referred to as members of the class. We will call the data items associated with an object the instance variables of that object (i.e. that instance of the class). Chapter 4 8

A Class as an Outline Chapter 4 9

Class Files and Separate Compilation Each Java class definition should be in a file by itself. The name of the file should be the same as the name of the class. The file name should end in.java A Java class can be compiled before it is used in a program The compiled byte code is stored in a file with the same name, but ending in.class Chapter 4 11

Class Files and Separate Compilation, cont. If all the classes used in a program are in the same directory as the program file, you do not need to import them. Chapter 4 12

Example class SpeciesFirstTry Chapter 4 13

Example, contd. The modifier public associated with the instance variables should be replaced with the modifier private, as we will do later in the chapter. Chapter 4 14

Example, contd. class SpeciesFirstTryDemo Each object of type SpeciesFirstTry has its own three instance variables Chapter 4 15

Using Methods two kinds of methods: methods that return a single value (e.g. nextint) methods that perform some action other than returning a single value (e.g println), called void methods Chapter 4 16

Methods That Return a Value example int next = keyboard.nextint(); keyboard is the calling object. You can use the method invocation any place that it is valid to use of value of the type returned by the method. Chapter 4 17

Methods That Do Not Return a Value example System.out.println( Enter data: ); System.out is the calling object. The method invocation is a Java statement that produces the action(s) specified in the method definition. It is as if the method invocation were replaced by the statements and declarations in the method definition. Chapter 4 18

void Method Definitions example public void writeouput() { } System.out.println( Name: + name); System.out.println( Age: + age); Such methods are called void methods. Chapter 4 19

Method Definitions All method definitions belong to some class. All method definitions are given inside the definition of the class to which they belong. If the definition of the method begins with public void, it does not return a value. public indicates that use is unrestricted. void indicates that the method does not return a value. Chapter 4 20

Method Definitions, cont. The parentheses following the method name contain any information the method needs. The first part of the method definition is called the heading. The remainder of the method is called the body, and is enclosed in braces {}. Statements or declarations are placed in the body. Chapter 4 21

Defining Methods That Return a Value example public int fivefactorial(); { } int factorial = 5*4*3*2*1; return factorial; As before, the method definition consists of the method heading and the method body. The return type replaces void. Chapter 4 23

Defining Methods That Return a Value, cont. The body of the method definition must contain return Expression; This is called a return statement. The Expression must produce a value of the type specified in the heading. The body can contain multiple return statements, but a single return statement makes for better code. Chapter 4 24

Naming Methods Use a verb to name a void method. void methods typically perform some action(s). (e.g. getage) Use a noun to name a method that returns a value. Methods that return a value are used like a value. (e.g. fivefactorial) Observe the convention of starting the method name with a lowercase letter. Chapter 4 25

Accessing Instance Variables Outside the class definition, a public instance variable is accessed with the name of an object of the class a dot (.) the name of the instance variable. Example: mybestfriend.name = Lara ; Inside the definition of the same class only the name of the instance variable is used. Example: name = keyboard.nextline(); Chapter 4 29

Accessing Instance Variables, cont. equivalent assignment statements: name = keyboard.nextline(); and this.name = keyboard.nextline(); The keyword this stands for the calling object - the object that invokes the method. Chapter 4 30

Local Variables A variable declared within a method is called a local variable. Its meaning is local to (confined to) the method definition. Variables with the same name declared within different methods are different variables. A local variable exists only as long as the method is active. Chapter 4 31

Blocks The terms block and compound statement both refer to a set of Java statements enclosed in braces {}. A variable declared within a block is local to the block. When the block ends, the variable disappears. If you intend to use the variable both inside and outside the block, declare it outside the block. Chapter 4 33

Parameters of a Primitive Type Often it is convenient to pass one or more values into a method and to have the method perform its actions using those values. The values are passed in as arguments (or actual parameters) associated with the method invocation. Chapter 4 36

Parameters of a Primitive Type, cont. The method receives the values and stores them in its formal parameters (or simply parameters). A method invocation assigns the values of the arguments (actual parameters) to the corresponding formal parameters (parameters). This is known as the call-by-value mechanism. Chapter 4 37

Parameters of a Primitive Type, cont. The formal parameters exist as long as the method is active. Chapter 4 38

Parameters of a Primitive Type, cont. Generally, the type of each argument must be the same as the type of the corresponding formal parameter. Java will perform automatic type conversion for an argument that appears to the left of a formal parameter it needs to match byte --> short --> int --> long --> float --> double Chapter 4 39

Parameters of a Primitive Type, cont. An argument in a method invocation can be a literal such as 2 or A a variable any expression that yields a value of the appropriate type. A method invocation can include any number of arguments; the method definition contains a corresponding number of formal parameters, each preceded by its type. Chapter 4 40

Parameters of a Primitive Type, cont. anobject.dostuff(42, 100, 9.99, Z ); public void dostuff(int n1, int n2, double d1, char c1); arguments and formal parameters are matched by position Everything said about arguments and formal parameters applies to methods that return a value as well as to void methods. Chapter 4 41

Information Hiding Information overload is avoided by suppressing or hiding certain kinds of information, making the programmer s job simpler and the code easier to understand. A programmer can use a method defined by someone else without knowing the details of how it works (e.g. the println method) She or he needs to know what the method does, but not how it does it. Chapter 4 47

Information Hiding, cont. What the method contains is not secret, and maybe not even interesting. Viewing the code does not help you use the method and may distract you from the task at hand. Designing a method so that it can be used without knowing how it performs its task is called information hiding or abstraction. Chapter 4 48

The public and private Modifiers The instance variables of a class should not be declared public. Typically, instance variables are declared private. An instance variable declared public can be accessed and changed directly, with potentially serious integrity consequences. Declaring an instance variable private protects its integrity. Chapter 4 55

The public and private Modifiers, cont. Analogy: An ATM permits deposits and withdrawals, both of which affect the account balance, but it does not permit an account balance to be accessed and changed directly. If an account balance could be accessed and changed directly, a bank would be at the mercy of ignorant and unscrupulous users. Chapter 4 56

The private Modifier The private modifier makes an instance variable inaccessible outside the class definition. But within the class definition, the instance variable remains accessible and changeable. This means that the instance variable can be accessed and changed only via the methods accompanying the class. Chapter 4 57

The private Modifier, cont. Statements such as System.out.println (secretspecies.population); are no longer valid. Chapter 4 59

The private Modifier, cont. Methods in a class also can be private. Methods declared private cannot be invoked outside the class definition, but can be invoked within the definition of any other method in the class. A method invoked only within the definition of other methods in the class should be declared private. Chapter 4 60

Accessor and Mutator Methods Appropriate access to an instance variable declared private is provided by an accessor method which is declared public. Typically, accessor methods begin with the word get, as in getname. Mutator methods should be written to guard against inappropriate changes. Chapter 4 61

Accessor and Mutator Methods, cont. Appropriate changes to an instance variable declared private are provided by an mutator method which is declared public. Typically, mutator methods begin with the word set, as in setname. Chapter 4 63

Encapsulation Encapsulation is the process of hiding details of a class definition that are not needed to use objects of the class. Encapsulation is a form of information hiding. Chapter 4 68

Encapsulation, cont. When done correctly, encapsulation neatly divides a class definition into two parts: the user interface which communicates everything needed to use the class the implementation consisting of all the members of the class. A class defined this way is said to be wellencapsulated. Chapter 4 69

The User Interface The user interface consists of the headings for the public methods the defined public constants comments telling the programmer how to use the public methods and the defined public constants. The user interface contains everything needed to use the class. Chapter 4 70

The Implementation The implementation consists of the private instance variables the private defined constants the definitions of public and private methods. The Java code contains both the user interface and the implementation. Imagine a wall between the user interface and the implementation. Chapter 4 71

Encapsulation Guidelines Precede the class definition with a comment that shapes the programmer s view of the class. Declare all the instance variables in the class private. Provide appropriate public accessor and mutator methods. Chapter 4 73

Encapsulation Guidelines, cont. Provide public methods to permit the programmer to use the class appropriately. Precede each public method with a comment specifying how to use the method. Declare methods invoked only by other methods in the class private. Use /*...*/ or /**...*/ for user interface comments and // for implementation comments. Chapter 4 74

Encapsulation Characteristics Encapsulation should permit implementation changes (improvements, modifications, simplifications, etc.) without requiring changes in any program or class that uses the class. Encapsulation combines the data and the methods into a single entity, hiding the details of the implementation. Chapter 4 75

ADT An abstract data type (ADT) is basically the same as a well-encapsulated class definition. Chapter 4 76

Variables Variables of a class type name objects, which is different from how primitive variables store values. All variables are implemented as memory locations. The value of a variable of a primitive type is stored in the assigned location. The value of a variable of a class type is the address where a named object of that class is stored. Chapter 4 82

Variables, cont. A value of any particular primitive type always requires the same amount of storage. example: a variable of type int always requires 4 bytes. An object of a class type might be arbitrarily large. An object of type String might be empty, or might contain 1, 120, 5280, or more characters. Chapter 4 83

Variables, cont. However, there is always a limit on the size of an address. The memory address where an object is stored is called a reference to the object. Variables of a class type behave differently from variables of a primitive type. Chapter 4 84

Allocating Memory for a Reference and an Object A declaration such as SpeciesFourthTry s; creates a variable s that can hold a memory address. A statement such as s = new SpeciesFourthTry(); allocates memory for an object of type SpeciesFourthTry. Chapter 4 89

== with Variables of a Class Type, cont. When used with variables of a class type, == tests if the variables are aliases of each other, not if they reference objects with identical data. To test for equality of objects in the intuitive sense, define and use an appropriate equals method. Chapter 4 91

Method equals The definition of method equals depends on the circumstances. In some cases, two objects may be equal when the values of only one particular instance variable match. In other cases, two objects may be equal only when the values of all instance variables match. Always name the method equals. Chapter 4 94

Boolean-Valued Methods A method that returns a value of type boolean is called a boolean-valued method. Method equals produces and returns a value of type boolean. The invocation of a boolean-valued method can be used as the condition of an if-else statement, a while statement, etc. Chapter 4 98

Boolean-Valued Methods, cont. The value returned by a boolean-valued method can be stored in a variable boolean areequal = s1.equals(s2); Any method that returns a boolean value can be used in the same way. Chapter 4 99

Class Parameters Recall When the assignment operator is used with objects of a class type, a memory address is copied, creating an alias. When the assignment operator is used with a primitive type, a copy of the primitive type is created. Chapter 4 100

Class Parameters, cont. When a parameter in a method invocation is a primitive type, the corresponding formal parameter is a copy of the primitive type. Chapter 4 101

Class Parameters, cont. When a parameter in a method invocation is a reference to a class type (i.e. a named object), the corresponding formal parameter is a copy of that reference (i.e. an identically valued reference to the same memory location). Chapter 4 102

Class Parameters, cont. Example if (s1.equals(s2)) public boolean equals (Species otherobject) causes otherobject to become an alias of s2, referring to the same memory location, which is equivalent to otherobject = s2; Chapter 4 103

Class Parameters, cont. Any changes made to the object named otherobject will be done to the object named s2, and vice versa, because they are the same object. If otherobject is a formal parameter of a method, the otherobject name exists only as long as the method is active. Chapter 4 104

Comparing Class Parameters and Primitive-Type Parameters A method cannot change the value of a variable of a primitive type passed into the method. A method can change the value(s) of the instance variable(s) of a class type passed into the method. Chapter 4 105

The Graphics Class An object of the class Graphics represents an area of the screen. The class Graphics also has methods that allow it do draw figures and text in the area of the screen it represents. Chapter 4 109

The Graphics Class, cont. Chapter 4 110

The Graphics Class, cont. A Graphics object has instance variables that specify an area of the screen In examples seen previously, the Graphics object represented the area corresponding to the inside of an applet. Chapter 4 111

The Graphics Class, cont. When an applet is run, a suitable Graphics object is created automatically and is used as an argument to the applet s paint method when the paint method is (automatically) invoked. The applet library code does all this for us. To add this library code to an applet definition, use extends JApplet Chapter 4 112

Programming Example class MultipleFaces Chapter 4 113

The init Method An init method can be defined when an applet is written. The method init (like the method paint) is called automatically when the applet is run. The paint method is used only for things like drawing. All other actions in an applet (adding labels, buttons, etc.) either occur or start in the init method. Chapter 4 117

Adding Labels to an Applet A label is another way to add text to an applet. Chapter 4 118

Adding Labels to an Applet, class LabelDemo cont. Chapter 4 119

The Content Pane Think of the content pane as inside of the applet. Container contentpane = getcontentpane(); When components are added to an applet, they are added to its content pane. The content pane is an object of type Container. Chapter 4 121

The Content Pane, cont. A named content pane can do things such as setting color contentpane.setbackground(color.white); or specifying how the components are arranged contentpane.setlayout (new FlowLayout()); Chapter 4 122

The Content Pane, cont. or adding labels JLabel label1 = new JLabel( Hello ); contentpane.add(label1); Chapter 4 123