Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.

Slides:



Advertisements
Similar presentations
1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference l Parameter passing Classes, Objects, and Methods.
Advertisements

JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Classes, Objects, and Methods
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Constructors. Defining Constructors  A constructor is a special kind of method that is designed to perform initializations, such as giving values to.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
Information Hiding and Encapsulation
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Parameters, Arguments, Local Variables, and Scope CSC 1401: Introduction to Programming with Java Week 8 – Lecture 1 Wanda M. Kunkle.
Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.
Introduction to Methods
Intro to CS – Honors I Classes and Methods GEORGIOS PORTOKALIDIS
COMP Classes Yi Hong May 22, Announcement  Lab 2 & 3 due today.
COMP More About Classes Yi Hong May 22, 2015.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Classes, Objects, and Methods
Comments are for people Header comments supply basic information about the artifact.
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.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Learners Support Publications Classes and Objects.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Day 5. Task: Implement your vending machine code into the program with JOptionPane I/O (modify it) it to me.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
COMP 150: Introduction to Object-Oriented Programming Lecturer: Dr. AJ Bieszczad 4-1 Chapter 4 l Class and Method Definitions l Information Hiding and.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Defining Classes and Methods Chapter 4. Object-Oriented Programming Our world consists of objects (people, trees, cars, cities, airline reservations,
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
COMP 110 Classes Luv Kohli October 1, 2008 MWF 2-2:50 pm Sitterson 014.
COMP 110: Introduction to Programming Tyler Johnson Feb 16, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
1 Week 8 l Methods l Parameter passing Methods. 2 Using Methods l Methods are actions that an object can perform. l To use a method you invoke or call.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Methods.
CPSC 233 Tutorial 5 February 9 th /10 th, Java Classes Each Java class contains a set of instance variables and methods Instance Variables: Type.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Defining Classes and Methods
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 21, 2011
3 Introduction to Classes and Objects.
Arrays in Classes and Methods
Methods.
Classes, Objects, and Methods
Defining Classes and Methods
Pemrograman Dasar Methods PTIIK - UB.
Classes and Objects.
Chapter 6 – Methods Topics are:
Introduction to Java Brief history of Java Sample Java Program
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
Lecture 5- Classes, Objects and Methods
Chapter 4 Defining Classes I
Object Oriented Programming in java
Defining Classes and Methods
Defining Classes and Methods
Classes, Objects and Methods
Announcements Assignment 2 and Lab 4 due Wednesday.
Basic Exception Handling
Presentation transcript:

Class and Method Definitions

UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void + stop(double howHardPress): void

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, and the file name should end in.java.  You can compile a Java class before you have a program in which to use it.  The compiled byte-code for the class will be stored in a file of the same name but ending in.class.

Class Files and Separate Compilation (cont’d)  Later you can compile a program file with a main part that uses classes that you have already compiled.  Every program with a main part has a class name at the start of the file; this is the name you need to use for the file that holds the program.  As long as all the classes you use in a program are in the same directory as the program file, you don’t need to worry about directories.

Example of a Class Definition import java.util.*; Public class Species { public String name; public int population; public double growthRate; public void readInput() { Scanner keyboard = new Scanner(System.in); System.out.println(“What is the species’ name?”; name = keyboard.nextLine(); System.out.println(“What is the population of the species?”); population = keyboard.nextInt(); while (population < 0) { System.out.println(“Population cannot be negative.”); System.out.println(“Reenter population:”); population = keyboard.nextInt(); } System.out.println(“Enter growth rate (percent increase per year:”); growthRate = keyboard.nextDouble(); }

Example of a Class Definition (cont’d) public void writeOutput() { System.out.println(“Name = “ + name); System.out.println(“Population = “ + population); System.out.println(“Growth rate = + growthRate + “%”); } public int populationIn10() { double populationAmount = population; int count = 10; while ((count > 0) && (populationAmount > 0)) { populationamount = (populationAmount + (growthRate/100)*populationAmount); count--; } if (populationAmount > 0) return (int)populationAmount; else return 0; }

Instance Variables  The class name in the previous example is Species.  The class is designed to hold records of endangered species.  Each object in the class has three pieces of data: a name, a population size, and a growth rate.  Objects of this class have three methods: readInput, writeOutput, and populationIn10.

Instance Variables (cont’d)  The data items and methods are called members of the object.  The data items are sometimes called fields, but we will refer to them as instance variables.  In the previous example the instance variables were name, population, and growthRate.  The word public simply means that there are no restrictions on how these variables are used.  An object is a complex item with instance variables inside it.

Example of a Program that Uses the Class Species public class SpeciesDemoProgram { public static void main(String[] args) { Species speciesOfTheMonth = new Species(); int futurePopulation; System.out.println(“Enter data on the Species of the Month:”); speciesOfTheMonth.readInput(); speciesOfTheMonth.writeOutput(); futurePopulation = speciesOfTheMonth.populationIn10(); System.out.println(“In ten years the population will be “ + futurePopulation); speciesOfTheMonth.name = “Klingon ox”; speciesOfTheMonth.population = 10; speciesOfTheMonth.growthRate = 15; System.out.println(“The new Species of the Month:”); speciesOfTheMonth.writeOutput(); System.out.println(“In ten years the population will be “ + speciesOfTheMonth.populationIn10()); }

Example of a Program that Uses the Class Species (cont’d)  You can refer to one of the instance variables of speciesOfThemonth by writing the object name followed by a dot and then followed by the instance variable’s name, e.g., speciesOfTheMonth.name  Each instance variable has a type, and the type of the previous example is String.

Example of a Program that Uses the Class Species (cont’d)  The new is used to create a new object of the class Species.  You can think of it as creating the instance variables of the object.

Using Methods  All methods perform some action or actions.  Some return a value, e.g., nextInt.  Some do not, e.g., println.  A method defined in a class is usually invoked using an object of that class. This object is known as the calling object, e.g., keyboard.nextInt();

Using Methods (cont’d)  You invoke a method by writing the calling object followed by a dot, then the name of the method, and finally a set of parentheses that may or may not have information to pass to the method.  If the method invocation returns a value, then you can use the method invocation anyplace that you are allowed to write a value of the type returned by the method, e.g., futurePopulation = speciesOfTheMonth.populationIn10();

Using Methods (cont’d)  If the method invocation does not return a value, then you place a semicolon after the method invocation and that produces a Java statement, e.g., speciesOfTheMonth.readInput();

Void Method Definitions  Each method definition is given inside the definition of the class to which it belongs.  The definition of a method that does not return a value starts with the keywords public void.  The word void means that nothing is returned.  The keyword public may be replaced with other words that restrict the use of the method.

Void Method Definitions (cont’d)  The first part of the method definition is called the heading.  The statements that follow, enclosed in braces { } are referred to as the body.  When a void method is invoked it is as if the method invocation were replaced with the body of the method where the instance variable names are replaced with those specific to the calling object, e.g., name is replaced by speciesOfTheMonth.name

Void Method Definitions (cont’d)  A program definition is just a class definition that has a method named main.  When you run a program you are simply invoking the void method that is name main.  The extra words static and String [] args will be explained later.

Methods that Return a Value  Methods that return a value are defined the same way as those that don’t with the following exceptions: Instead of the word void the type of the value returned by the method is given, e.g., public int populationIn10() The body of the method must contain one or more return statements to return a value, e.g., return (int)populationAmount;

Naming Methods  Choose clear meaningful names.  It’s usually a good idea to use verbs to name methods that perform some action but do not return values, e.g. println.  Nouns are usually the best choice for methods that return a value, e.g., populationIn10.  By convention, methods begin with lowercase letters, and class names begin with uppercase

Use of return in void Methods  A return statement can also be used in methods that do not return values just to cause the method to terminate and return control to the method it was invoked from.  In this case you simply say return; with nothing following the return.

The this Parameter  When giving a method definition, you can use the keyword this as a name for the calling object.  For example, in the definition the writeOutput() method of the Species class we wrote, System.out.println(“name = “ + name); We could have written, System.out.println(“name = “ + this.name);

The this Parameter (cont’d)  You can think of this as just a place holder for the calling object to be given when the method is invoked.  this is usually omitted although there are some situations where it is needed.

Local Variables  Methods usually declarations for variables used within them beyond those declared in the class.  These are local to the method in which they are declared and cannot be used outside the method.  Two methods may have variables of the same name but they are treated as separate variables.

Blocks  A block is any set of Java statements enclosed within braces ({}).  Sometimes blocks are referred to as compound statements.  If you declare a variable within a block, it is not valid outside the block.  In Java you cannot use the same name for different variables in different blocks even though it is valid only in the block where it is declared.

Parameters of a Primitive Type  The method populationIn10 for the class Species returns the projected population of a species 10 years in the future.  If we wanted to generalize this method to calculate the projected population for any number of years in the future we could pass number of years as a parameter to the method.

Revised Method for Projecting Population public int projectedPopulation(int years) { double populationAmount = population; int count = years: while ((count > 0) && (populationAmount > 0)) { populationamount = (populationAmount + (growthRate/100)*populationAmount); count--; } if (populationAmount > 0) return (int)populationAmount; else return 0; }

Example of Using a Method with a Parameter public class SpeciesDemoProgram2 { public static void main(String[] args) { Species speciesOfTheMonth = new Species(); int futurePopulation; System.out.println(“Enter data on the Species of the Month:”); speciesOfTheMonth.readInput(); speciesOfTheMonth.writeOutput(); futurePopulation = speciesOfTheMonth.projectedPopulation(10); System.out.println(“In ten years the population will be “ + futurePopulation); speciesOfTheMonth.name = “Klingon ox”; speciesOfTheMonth.population = 10; speciesOfTheMonth.growthRate = 15; System.out.println(“The new Species of the Month:”); speciesOfTheMonth.writeOutput(); System.out.println(“In ten years the population will be “ + speciesOfTheMonth.projectedPopulation(10)); }

Formal Parameters and Arguments  In the projectedPopulation(int years) method definition the word years is called a formal parameter or simply a parameter.  It is a stand-in for a value that will be plugged in when the method is invoked.  The item that is plugged in is called an argument ( or sometimes an actual parameter).

Formal Parameters and Arguments (cont’d)  In the invocation: futurePopulation = speciesOfTheMonth.projectedPopulation(10); the value 10 is an argument.  It is important to note that only the value of the argument is used in this substitution process. If the argument is a variable only the value of the variable is plugged in, not the name of the variable. This is called call-by-value.

Correspondence Between Formal Parameters and Arguments  Formal parameters are given in parentheses after the method name at the beginning of a method definition.  In a method invocation, arguments are given in parentheses after the method name.  There must be exactly the same number of arguments as formal parameters, and they must be given in the same order.