PART 3. You have been using static methods in your programs before and methods are the building blocks of procedural programming. In this part of the.

Slides:



Advertisements
Similar presentations
Copyright © Texas Education Agency, Computer Programming Class Basics.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 6: A First Look at classes. Object-Oriented Programming  Object-oriented programming is centered on creating objects rather than procedures.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Fibonacci Numbers A simple example of program design.
20-Jun-15 Methods. Complexity The programmer's biggest adversary is complexity The programmer's biggest adversary is complexity Primitive types and the.
Enhancing classes Visibility modifiers and encapsulation revisited
Understanding class definitions Looking inside classes.
A tour around Java General introduction to aspects of the language (these will be covered in more detail later) After this tour you should have a general.
Unit 2: Java Introduction to Programming 2.1 Initial Example.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Object Oriented Software Development
PART 2 Part 2: The Material. With the introduction of what an object is, now we are ready to learn the CONSTRUCTOR concept. And when we want to make use.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
Java Classes Using Java Classes Introduction to UML.
4.1 Instance Variables, Constructors, and Methods.
Creating Simple Classes. Outline of Class Account Class Account Account # Balance Holder name phone# Overdrawn (true/false) Data Members Open Credit Debit.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Java Classes Methods Objects. Classes Classes We have been using classes ever since we started programming in Java Whenever we use the keyword class.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Summer Computing Workshop. Introduction  Boolean Expressions – In programming, a Boolean expression is an expression that is either true or false. In.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Methods We write methods in our programs for many reasons:
PART 1 Part 1: The Material. Whether you knew it or not, all the programming that you have performed until now was in the boundaries of procedural programming.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Newport Robotics Group 1 Tuesdays, 6:30 – 8:30 PM Newport High School Week 4 10/23/2014.
1 CS 177 Week 11 Recitation Slides Class Design/Custom Classes.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
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.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
OOP Basics Classes & Methods (c) IDMS/SQL News
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Class Definitions and Writing Methods Chapter 3 3/31/16 & 4/4/16.
Class Definitions: The Fundamentals Chapter 6 3/30/15 & 4/2/15 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has.
A Simple Object Oriented Program public class Simple { public static void main (String [] args) { System.out.println(“howdy”); } System.out is an object.
1 CSC 221: Computer Programming I Fall 2005 graphics & design  Dot & DotRace revisited  Circle class implementation  adding Circle methods  static.
Topic: Classes and Objects
More Sophisticated Behavior
Concepts of Object Oriented Programming
Building Java Programs
Building Java Programs
Chapter 5 Classes.
Lesson 2: Building Blocks of Programming
A simple example of program design
Group Status Project Status.
Building Java Programs
Java Programming Function Introduction
COS 260 DAY 4 Tony Gauvin.
Building Java Programs
Week 4 Lecture-2 Chapter 6 (Methods).
Building Java Programs
Building Java Programs
Building Java Programs
Java Programming Function Introduction
Lecture 8-2: Object Behavior (Methods) and Constructors
Presentation transcript:

PART 3

You have been using static methods in your programs before and methods are the building blocks of procedural programming. In this part of the tutorial we will introduce non-static methods, i.e. methods that are inside non-static classes. The idea of having methods in a non-static class can be confusing at first since we introduced non-static classes as a way defining new, more elaborate data types called objects. The ability to put methods inside these classes means that objects are more than just serving as a new data type. They are much more powerful. Part 3: The Material

We will start by explaining why non-static methods are useful. In principle, non-static methods do not give programmers any extra power because anything one can do using non- static methods can be done using static methods. Then why do we need non-static methods? The heart of object-oriented programming is the ability to reuse someone else’s code without even looking at the code itself. This is extremely important when developing big projects. But code reusability would not mean much if we were not able to reuse someone else’s methods. Part 3: The Material

The ability to put methods in non-static classes means that we can use other people’s methods without knowing the details of how it is implemented. With non-static methods, object oriented programming gets interesting. All this will be better understood with an example. Part 3: The Material

Let’s create a non-static class called Box which has three fields: int height, int width, int depth. class Box { int height; int width; int depth; Box(int h, int w, int d) { height = h; width = w; depth = d; } Part 3: The Material

Now that we have defined this Box class, we can create Box objects of any dimension. Suppose we needed to calculate the surface area and the volume of a number of boxes. For this purpose we can define two methods which take a Box as a parameter and return the Box’s surface area and volume respectively. class Application { static void main(String args[]) { Box b1 = new Box(3,4,5); Box b2 = new Box(2,1,4); Box b3 = new Box(2,2,2); } Part 3: The Material

class Application { static void main(String[] args) { Box b1 = new Box (2,3,4); Box b2 = new Box (1,3,2); System.out.println(“The surface area of the first box is ” + calculateSurfaceArea(b1) + “.”); System.out.println(“The volume of the second box is ” + calculateVolume(b2) + “.”); } static int calculateSurfaceArea(Box b) { return 2 * b.height * b.width + 2 * b.height * b.depth + 2 * b.width * b.depth; } static int calculateVolume(Box b) { return b.height * b.width * b.depth; } Part 3: The Material

The surface area and volume methods are very natural methods that any Box object should come equipped with. In other words, any person who has downloaded the Box class should not have to write the code for these methods. Somehow, these methods should reside in the Box object and any person should be able to use them without even knowing the details of the code inside them. This is accomplished by putting these methods inside the Box class. When we do this, we will get rid of the “static” keyword and these methods will become non-static methods. Part 3: The Material

class Box { int height; int width; int depth; Box(int h, int w, int d) { height = h; width = w; depth = d; } int calculateSurfaceArea() { return 2 * height * width + 2 * height * depth + 2 * width * depth; } int calculateVolume() { return height * width * depth; } Part 3: The Material

The careful reader will notice a difference in the calculateSurfaceArea and the calculateVolume non-static methods. For example let’s look at the calculateSurfaceArea method. To understand why such a difference exists, it is a good idea to look at how we call the non-static methods in our static class. static int calculateSurfaceArea(Box b) { return 2 * b.height * b.width + 2 * b.height * b.depth + 2 * b.width * b.depth; } int calculateSurfaceArea() { return 2 * height * width + 2 * height * depth + 2 * width * depth; } Part 3: The Material

In this code, we create two Box objects b1 and b2. Each of these objects has its own fields: int height, int width, int depth. On top of these, they come with two methods: calculateSurfaceArea and calculateVolume. Recall that we use the dot operator to access these objects’ fields. Similarly, we use the dot operator to access the objects’ methods. class Application { static void main(String[] args) { Box b1 = new Box (2,3,4); Box b2 = new Box (1,3,2); System.out.println(“The surface area of the first box is ” + b1.calculateSurfaceArea() + “.”); System.out.println(“The volume of the second box is ” + b2.calculateVolume() + “.”); } Part 3: The Material

Now let’s go back to the non-static vs. static comparison. In the static version, we have to give the object as a parameter since a static method does not belong to a particular object. In the non-static version, we do not need to do this since the method is attached to an object already. Also note that in the static version we have to access the fields of the object using the dot operator. In the non- static version, we directly use the names of the fields because the non-static method has direct access to the fields of the object that it belongs to. static int calculateSurfaceArea(Box b) { return 2 * b.height * b.width + 2 * b.height * b.depth + 2 * b.width * b.depth; } int calculateSurfaceArea() { return 2 * height * width + 2 * height * depth + 2 * width * depth; } Part 3: The Material

class Box{ int height; int width; int depth; Box(int h, int w, int d){ height = h; width = w; depth = d; } class Application { static void main(String[] args) { Box b1 = new Box (2,3,4); Box b2 = new Box (1,3,2); System.out.println( calculateSurfaceArea(b1)); System.out.println( calculateVolume(b2)); } static int calculateSurfaceArea(Box b) { return 2 * b.height * b.width + 2 * b.height * b.depth + 2 * b.width * b.depth; } static int calculateVolume(Box b) { return b.height * b.width * b.depth; } class Box{ int height; int width; int depth; Box(int h, int w, int d) { height = h; width = w; depth = d; } int calculateSurfaceArea() { return 2 * height * width + 2 * height * depth + 2 * width * depth; } int calculateVolume() { return height * width * depth; } class Application { static void main(String[] args) { Box b1 = new Box (2,3,4); Box b2 = new Box (1,3,2); System.out.println( b1.calculateSurfaceArea()); System.out.println( b2.calculateVolume()); } Part 3: The Material

Now let’s demonstrate how this transition may be useful to programmers all around the world. Suppose you are the creator of the Box class and you share this class with everyone through the internet. Along with your program, you give a documentation. In the documentation, you provide the following information. Constructor Box(int h, int w, int d) Creates a box with height h, width w and depth d. Methods int calculateSurfaceArea() 1) int calculateSurfaceArea() Returns the surface area of the box. int calculateVolume() 2) int calculateVolume() Returns the volume of the box. Part 3: The Material

Any person who has downloaded your class can now use it without even looking at one line of the code. S/he can create Box objects of any dimension and can calculate the volume or surface area very easily. Conveniently, people using this object do not have to know the formula for calculating the surface area of a box. On the internet, one can find many many classes along with their documentation. Some of these classes contain complicated code. But we do not need to know the code to use this class and its methods. This is how one creates big projects: by using previously created classes and not worrying about how it was implemented. class Application { static void main(String args[]) { Box b = new Box(3,4,2); System.out.println(“Surface area of the box is ” + b.calculateSurfaceArea() + “.”); } Part 3: The Material

Non-static methods can be used for many purposes such as Altering the state of the object Provide some information about the object Make a calculation using the fields of the object Certainly the uses of these methods are not limited to above. With what Java allows you with object oriented programming, your imagination is the limit. Now let’s see an example which demonstrates some of the different uses of non-static methods. Part 3: The Material

class Beer{ int amount; Beer(int a){ amount = a; } void drink(int d){ amount = amount – d; } void chuck(){ amount = 0; } void print_amount(){ System.out.println(amount); } boolean is_empty(){ if(amount == 0) return true; else return false; } class Application { static void main(String[] args) { Beer b = new Beer(15); b.print_amount(); b.drink(5); if(b.is_empty()) System.out.println(“No more beer.”); b.print_amount(); b.chuck(); b.print_amount(); if(b.is_empty()) System.out.println(“zzzzz”); } Part 3: The Material

Review of Concepts Apart from the fields and constructors, an object could also include methods. These methods could be used for a variety of reasons: Make a sophisticated calculation using the values of the fields of the object Print out some information about the object Modify the values of the fields of the object Revisiting the reusability: With the addition of methods, the sharing of code concept should become more clear. Let’s say you implement the Box class. The class has fields, constructors and methods. A friend of yours, who is in need of a Box object in his/her application, may use this Box class that you have written, without even knowing the formula to calculate the surface area. Part 3: The Review

Review of Syntax In order to add a method to the class declaration: returnType methodName(parameters) { // your code goes here... } Part 3: The Review

Exercise Write a simple class to represent elevators. An elevator has a current floor, number of floors, current number of passengers and maximum number of passengers. An elevator: Is constructed by specifying: –the total number of floors in the building –the maximum elevator capacity –that the elevator initially doesn’t have any passengers –and that the elevator is initially located on the bottom floor. Can move one floor up if it is not on the top floor. Can move one floor down if it is not on the bottom floor. Can accept a certain number of passengers (up to its maximum capacity). Can drop off a certain number of passengers (no more than it actually has). Can tell us which floor it is on. Part 3: The Exercise

Solution class Elevator{ int currentFloor; int numFloors; int currentPassengers; int maxPassengers; Elevator(int maxFloors, int capacity){ numFloors = maxFloors; maxPassengers = capacity; currentFloor = 1; currentPassengers = 0; } void moveUp(){ if(currentFloor < numFloors) currentFloor++; } void moveDown(){ if(currentFloor > 0 ) currentFloor--; } Part 3: The Solution

boolean acceptPassengers(int num){ boolean result = true; int difference = maxPassengers – currentPassengers; if(difference > 0 && num > 0){ if(num < difference) currentPassengers += num; else currentPassengers += difference; } else result = false; return result; } boolean dropOffPassengers(int num){ boolean result = true; if(num 0) currentPassengers -= num; else{ if(num > currentPassengers) currentPassengers = 0; else result = false; } return result; int getCurrentFloor(){ return currentFloor; } } // end of class Elevator Part 3: The Solution