Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.

Slides:



Advertisements
Similar presentations
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
Advertisements

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Lecture 2 Basics of C#. Members of a Class A field is a variable of any type that is declared directly in a class. Fields are members of their containing.
Road Map Introduction to object oriented programming. Classes
Programmer-defined classes, part 2 More on identifier scope & Parameter passing.
Java: How to Program Methods Summary Yingcai Xiao.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
Chapter 6: Functions.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Writing Classes (Chapter 4)
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Creating Simple Classes. Outline of Class Account Class Account Account # Balance Holder name phone# Overdrawn (true/false) Data Members Open Credit Debit.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Chapter 11: Introduction to Classes. In this chapter you will learn about: – Classes – Basic class functions – Adding class functions – A case study involving.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
CSC Programming I Lecture 6 September 4, 2002.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
SEEM Java – Basic Introduction, Classes and Objects.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Topic: Classes and Objects
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Methods Chapter 6.
Chapter 6 Methods: A Deeper Look
Classes & Objects: Examples
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Presentation transcript:

Classes with multiple methods Part 1

Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs –Classes describe objects –Objects are instances of classes A programmer-defined class is any class that isn’t in the Java API

Class methods & data A class definition generally consists of: –A set of methods that perform tasks –A set of data that can be manipulated by these methods To design a class: –Think about the thing we want to model –Come up with a list of tasks we want that thing to do

Example: a thermometer A thermometer is an instrument that measures temperature and displays its reading The set of operations is: –Measure temperature –Display temperature

Enhanced thermometer We’re going to look at a thermometer with somewhat enhanced capabilities Instead of just displaying the temperature measured, the enhanced thermometer can display its measurement in three different scales: Celsius, Fahrenheit, and Kelvin

Data members Class-wide data are stored in variables or constants Such data belong to an object (or to a class) and not to any particular method within the object Such data are accessible to all methods of the class A thermometer object needs to have a variable to store its unique temperature reading, and constants to use for converting the value between the 3 scales

Data members in BetterTherm class The class-wide data declarations appear at the beginning of the class: public class BetterTherm { private int kelvinTemp; private final static int CFACTOR = 273; private final static int RANGE = 101; private final static int FCONVI = 32; private final static double FCONVD = 1.8;

Instance variables There is one variable declared on the previous slide: private int kelvinTemp; –This is an instance variable; that is, it belongs to an instance of the class (in other words, an object) –Every instance of the class will have its own copy of this variable, so every object of this type could have a unique temperature value

Class constants All of the constants, such as the one below, differ from the variable not only because they are constants, but because the keyword static in their declaration indicates that they belong to the entire class, not to any particular class instance: private final static int CFACTOR = 273;

Class constants If a class member (either data or method) is declared static, its existence is independent of any particular object: –All objects of the class type share such members, rather than having their own copies –The class member exists even if there are no class instances; this is how it is possible for us to access the PI constant from the Math class even though we never create Math objects

Visibility modifiers The keywords public and private are used to indicate whether or not access to the declared item is restricted to class members If a variable, constant, or method is declared private, then it can only be “seen” by members of its class If declared public, visibility extends outside the class In most cases, variables are declared private, while methods are declared public If no visibility modifier is given, the default is private

Defining methods In the examples we’ve seen in the past, each class contained a single method, named main For this class, we’ll define a more conventional set of methods: –Constructor: a method that defines the default characteristics of an object –Accessors: methods that provide access to the data values in the class –Mutators: methods that change the data values in a class

Constructor The constructor for a Java class is a special method used to initialize data members of the object being created It has the following unique characteristics: –Always public –No return type –Same name as the class The next slide shows a constructor for the BetterTherm class

BetterTherm Constructor public BetterTherm () { Random temp = new Random(); kelvinTemp = Math.abs(temp.nextInt()); kelvinTemp = kelvinTemp % RANGE + CFACTOR; // initializes the temperature to somewhere between // 273K and 373K - the freezing point and boiling point // of water, respectively, on the Kelvin scale }

BetterTherm Constructor The purpose of the constructor is to set a default value for the instance variable kelvinTemp The default value is a random number between 273 and 373 methods within a class have access to variables and constants declared as part of the same classBecause the method (BetterTherm) and the variable (kelvinTemp) are members of the same class, there is no need to pass an argument to BetterTherm (the method); methods within a class have access to variables and constants declared as part of the same class For the same reason, the constructor has access to CFACTOR and RANGE, two of the class constants

Local variables Besides kelvinTemp, there is another variable used in the constructor: the random number generator object, temp This variable is declared within the BetterTherm method localSince it is declared within the block of code comprising the body of the method, we say that this variable is local to the method

Scope of identifiers The locality of the temp variable is referred to as its scope; the more local the scope, the more restricted its accessibility A local variable can only be referenced within the block where it’s declared The scope of instance variables and class constants is wider; we can refer to these from anywhere within the class, as we have already seen

Accessor methods Accessor methods provide a kind of a window into the private world of the class –An analogy: your thoughts are private, but you can give the outside world access to them by putting your thoughts into words –Even though the world can now “see” your thoughts, they still belong to you, and only you can change your mind In a similar way, accessor methods allow the world to see the values of private data members of an object, but only the object can change these values (via mutator methods)

Accessor methods Because the purpose of an accessor is to make a value visible, this type of method always has a return type other than void return statementSuch methods must contain a return statement –Typically the last statement in a method –When this statement executes, the method ends –The value returned is represented by an expression which must evaluate to a result of the return type of the method

Two example accessors from BetterTherm // return Kelvin temperature public int getKelvin () { return kelvinTemp; } // Convert to Celcius & return public int getCelcius () { return kelvinTemp - CFACTOR; } Both methods have an int return type, so each one has a return statement containing an integer expression. Simple accessor methods like this are sometimes called “getter” methods.

One more example We declare local variable fTemp to hold the return value The method could have been written with just a return statement, but it’s a little easier to read this way // Convert to Fahrenheit & return public int getFahrenheit () { int fTemp; // Fahrenheit temperature to be returned fTemp = (int)(FCONVD * getCelcius()) + FCONVI); return fTemp; }

The general model for a method The generic syntax for a method is: Modifier(s) returnType identifier (parameter(s)) { method body return statement (if needed) } Where: Modifiers include public, private, and static returnType is a simple type, class type, or void A return statement is necessary unless the method is declared void

Static methods As we have seen, static constants belong to the class, rather than to an object We have seen numerous examples of Java methods that are called using messages associated with classes rather than objects (the Math methods, JOptionPane methods, etc.) These are examples of static methods

Static methods static methods can only access other static class membersStatic methods differ from non-static methods in another important way; static methods can only access other static class members (variables, constants or methods) The main method is always declared static; in order to use the main method to test non-static members of the class, you must declare an object of the class type and call the methods from that object

A main method for BetterTherm public static void main (String [] args) { BetterTherm bt1, bt2, bt3; bt1 = new BetterTherm(); bt2 = new BetterTherm(); bt3 = new BetterTherm(); System.out.println ("The three thermometers are reading as follows:"); System.out.println ("\tK\tC\tF"); System.out.println ("1)\t" + bt1.getKelvin() + "\t" + bt1.getCelsius() + "\t" + bt1.getFahrenheit()); System.out.println ("2)\t" + bt2.getKelvin() + "\t" + bt2.getCelsius()+ "\t" + bt2.getFahrenheit()); System.out.println ("3)\t" + bt3.getKelvin() + "\t" + bt3.getCelsius() + "\t" + bt3.getFahrenheit()); }

Main method The main method presented on the previous slide creates three thermometer objects, then shows their temperature readings in the three different scales The output looks something like this: The three thermometers are reading as follows: KCF 1) ) )

Main method The main method can either be declared as part of the class or in a separate tester class An example of a tester class is shown below: public class TestTherm { public static void main (String [] args) { // same body as previously shown }