Chapter 5- Even more about objects and methods. Overview n Designing methods n Methods, methods, methods n Overloading methods n Constructor methods n.

Slides:



Advertisements
Similar presentations
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Advertisements

Road Map Introduction to object oriented programming. Classes
Chapter 5 Part 1 COSI 11a Prepared by Ross Shaull.
Access to Names Namespaces, Scopes, Access privileges.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
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.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Writing Classes (Chapter 4)
Writing Classes You have already used classes –String, Random, Scanner, Math, Graphics, etc –To use a class: import the class or the package containing.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
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.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 6- Arrays. Overview n What are arrays? n Declaring/initializing arrays. n Using arrays. n Arrays details. n Using arrays with classes/ in classes.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
10-Nov-15 Java Object Oriented Programming What is it?
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Session 7 Methods Strings Constructors this Inheritance.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
The Math Class Methods Utilizing the Important Math Operations of Java!
More Object Concepts— Farrell, Chapter 4 Dr. Burns.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
Chapter 8-Exception Handling/ Robust Programming.
Classes - Intermediate
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Methods. Creating your own methods Java allows you to create custom methods inside its main body. public class Test { // insert your own methods right.
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
Chapter VII: Arrays.
Chapter 5: Enhancing Classes
User-Written Functions
Chapter 3: Using Methods, Classes, and Objects
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Chapter 4: Writing Classes
Namespaces, Scopes, Access privileges
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Lecture 11 C Parameters Richard Gesick.
Group Status Project Status.
CHAPTER 6 GENERAL-PURPOSE METHODS
Chapter 4 Writing Classes.
Chapter 6 Methods.
Namespaces, Scopes, Access privileges
Week 4 Lecture-2 Chapter 6 (Methods).
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Object Oriented Programming in java
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming Language
In this class, we will cover:
Corresponds with Chapter 5
Presentation transcript:

Chapter 5- Even more about objects and methods

Overview n Designing methods n Methods, methods, methods n Overloading methods n Constructor methods n Static methods and variables n Math class and static methods n Information Hiding again n Packages

Method Design

Designing methods n Now that we are starting to get into some larger programs, things can get a lot more difficult very quickly. Design becomes more and more important from here on out. n Every class can have as many methods as we want, but how many do we really want? And what do they need to do?

Designing steps n Determine what you need the class to do. (Like the class exercise). n Figure out what types of data you need. n Write down the method declarations (the names and the types taken/returned) that you need. n Design the methods next.

Designing Methods n Write in English what the method should do. n Write pseudocode for what the major steps should be in the method. n Fill in the pseudocode with actual Java code to finish out the method.

Pseudocode n A mixture of plain English and whatever programming language you are using. for(I = 1 to 20) { add I to the sum. Print out the sum. System.out.println(sum); }

Filling in the pseudocode n Fill in any English with Java code. for(I = 1 to 20) { add I to the sum. Print out the sum. System.out.println(sum); } for(I = 1; I <=20; I++) { sum+=I; System.out.println(sum); }

Keep refining step by step. n The previously described method is sometimes called the top-down method or stepwise refinement. n Just slowly chisel away at large problems, refining the design one step at a time until you get to code.

More details about methods

Methods are everywhere… n You can have as many methods as you want in a class. n Not all of them have to be public, any ones that you don’t want accessible outside of the class can be made private. n You can call methods from other methods (in fact this is the only way we do call methods). n Can also have a main method in every class.

Example of methods within methods(suppose instanceInt is a private variable for the class)… public void enterInt() { System.out.println(“Enter an integer:”); instanceInt = SavitchIn.readLineInt(); displayInfo(); } public void displayInfo() { System.out.println(“The integer stored” + “ is “ + instanceInt); } Could also use this.displayInfo();

Having a main method in every class. n Having a main method in every class can be a good tool in debugging problems. n When making a class, make a main method in it to test the functionality. n Be careful that in your main method you are not taking liberties that others won’t have when trying to use your class (you will have access to private information/methods). DON’T make calls to private methods or access private data from your main method! n The only main method that is called when your program starts is the one that has the same name as in the java command (or whatever file is visible in TextPad when you use the run command).

From now on… n Homework assignments can all be done in one file if you wish (sometimes it is nicer to have more than one file though). You can write the class and have the testing program located inside that same class (inside the main method). Using private methods or accessing private data is not acceptable, though, so be careful.

Things not to do in your main method public class Triangle { private double base, height; … public static void main(String [] args) {Triangle a = new Triangle(); System.out.println(“The base is: “ +a.base); System.out.println(“The height is:”+a.height); } Should use a.getBase() and a.getHeight()

Overloading methods

n Method overloading is the act of having multiple methods in a class that have the same name. n Each overloaded method has to have different parameters than any of the other methods. n When that method name is invoked, the number and type of arguments in the invocation determine which method is called.

Method overloading examples. public int add(int num1, int num2) {return (num1+num2); } public char add(char let1, char let2) {let2 =(char)((int)let2 – (int)’a’); return(char)((int)let1 + (int)let2); } public int add(int num1, int num2, int num3) {return num1+num2+num3; } public String add(String phrase1, int num1) {return phrase1 + num1; } add(1,2) = 3add(‘b’,’b’) = ‘c’ add(1,2,3) = 6add(“Hello”,3) = “Hello3”

Things to be careful about n The parameters have to be different, but the return type is ignored. The following would be invalid: public int add(int num1, int num2){…} public double add(int num1, int num2){…} n Automatic conversions on the data types being passed in can have unexpected results in just which method is called. add(‘1’,’2’) = ?.

Are the following sets of method headers valid for overloading? public void method1(int num1, int num2); public void method1(); public void method1(int num1, double num2); public void method1(char num1, char num2); public void method2(int num1, int num2); public double method2(int num1, int num2); public char method2(int num1, int num3); public void method3(int num1); public double method2(int num1, int num2); public double method3(int num1, int num2, int num3); Yes No, the types are the same. Yes

Constructors

n Constructors are very special methods of a class. They have the exact same name as the class and are only called when you create an object of the class. n If you do not specify any constructors, Java will provide one for you (though it may not act as you want). n Constructors are never static (later) and never return any information. They are mainly just for initializing your objects.

More constructors n Constructors are often overloaded. n Often have a constructor for every possible combination of data initializations. n This way users can create a new item and initialize it to some value in one step. n A constructor with no parameters is called a default constructor.

Constructor examples public class Muglet { private int number; public Muglet() { number = 0; } public Muglet(int numIn) { number = numIn; } } Called a default constructor(no args)

Using the Constructor example public class MugletTest { public static void main(String [] args) { Muglet muglet1 = new Muglet(); Muglet muglet2 = new Muglet(45); }

Constructors with more data types public class Muglet { private int number; private int otherNumber; private String name; public Muglet(){…} public Muglet(int aNumber) {…} public Muglet(String aName) {…} public Muglet(int aNumber, int anotherNumber){…} public Muglet(int aNumber, int anotherNumber, String aName){…} } Note there is no Muglet(int anotherNumber) constructor, as it would look the same as Muglet(int aNumber). This would break the overloading.

Which are not valid groups of constructors for the class Muglet. public Muglet(){…} public Muglet(int a, int b){…} public Muglet(int b, int c){…} public Muglet(double g, int c){…} public Muglet(){…} public Muglet(int a){…} public Muglet(double a){…} public Muglet(String a){…} public Muglet(String a, int a, double a){…}

What constructors might we want? n If the class Muglet contained just one private integer instance variable? n If the class Blar contained one private String and one private double instance variables?

Static variables and methods

Static methods n Static methods are methods that can be called without a calling object (it is called with the class instead). n Math and SavitchIn are examples of classes that have static methods. n What is a static method that we ourselves have already been programming?

Example of using static methods int readInt = SavitchIn.readLineInt(); double exponent = Math.pow(4.0,5.0); int absolute = Math.abs(readInt); Classes, not objects. Static methods.

Making static methods. n Can’t use any instance variables. Can only access static variables (we’ll get to that in minute). n Can’t use any instance methods(nothing that would use “this”). n Just put the word static in between the public/private modifier and the return type of the method: public static void main(String [] args) public static double area(double radius)

Static variables n Not associated with any one object, it’s associated with all objects of a class. n “Class-wide” variables. Every object of the class can see the same variable, and it is the same value for all of the objects. n Good way of keeping counts of the number of objects created, or for keeping constants that all objects need access to.

Example of creating static methods public class Muglet { public static int number; public String name; public Muglet(String someString) { this.name = someString; number++; } public static void mugletReport() { System.out.println("You have made " + number + " Muglets"); }

Using the previous example public class MugletTest { public static void main(String []args) { Muglet.mugletReport(); Muglet muglet1 = new Muglet(“1”); Muglet muglet2 = new Muglet(“15”); Muglet muglet3 = new Muglet(“Arr”); Muglet.mugletreport(); } 0 3

Math class and the random method

Math methods n The Math class has a TON of useful static methods that you can use. n We have already seen a few in the last section such as abs and pow. n We will concentrate on the random method in this section.

random method. n When we call Math.random(), it will give us a double value greater than or equal to 0.0 and less than 1.0. n We can use the multiply and addition operators as well as integer casts to make this any sort of random integer range.

random examples x = Math.random(); //0.0<= x < 1.0 x = Math.random()*2; //0.0 <= x < 2.0 x = Math.random()*2 + 1; //1.0<=x < 3.0 x = (int)(Math.random()*2 +1); //1<=x<=2 x = (int)(Math.random()*6 + 1); //1<=x<=6 x = (int)(Math.random()*6 +1)*3; //x is one of 3,6,9,12,15,18.

What to use the random function for n Basically, games. n Whenever you need a random event to occur, create a random number and choose the event based on the number. n Now you can start making very basic games of chance (once we do arrays, you’ll be able to do about everything for games except graphics).

Tricks in Information Hiding…

Keeping private data private n If you have a private instance Class variable(you have an object as one of your private instance variables), it is a good idea not to return the object from your methods. n The object you return, though private, is an actual memory address, so people can take that memory address and corrupt the data that it points to.

Keeping private data private n You don’t have to worry about what you return if you are only returning primitives or a String. n If you want to be safe with objects, you’ll want to return a clone of the object (use the clone() method, assuming it is provided in the object’s class).

Packages

n There are hundreds of libraries out there that have pre-written code from other people and companies that we can use in our program. n To use these libraries, called packages, we need to just use and import statement. import java.text.*;//import all classes //from java.text package

Our own packages n We can even make our own libraries of classes for other people to use. n To make a collection of classes into a package, you only need to put a package statement at the top of each class you want to include. package org.eggnogg.roborally; package com.ibm.widgets;

Package details n To compile code correctly from packages, the package must be in specific directory that is related to the package name. n For details on this, see java.sun.com or read more in Chapter 5 about packages.

Review

Chapter Review- Designing n What is the topdown design method, in your own words? n What languages are used in pseudocode?

Chapter Review- Method Details n Is there a limit to the number of methods you can have in a class? How many? n Can you call another method from inside of a method? n Can you have a main method in every class? Which classes can’t you have them in?

Chapter Review- Overloading n What is overloading? n What has to be different about two methods if we wish to have one of them overload the other one? n What role does the return type play in overloading? n Is the following valid? public int method1(int number1){…} public int method1(double number1){…}

Chapter Review-Constructors n What are constructors? What are they usually used for? n How do you specify that a method is a constructor? n What type does a constructor method return? n Can you overload constructors?

Chapter Review-Static stuff n What is the difference between a static method and an instance method? n What is the difference between a static variable and an instance variable? n What types of variables can’t you use in static methods? n What types of variables can’t you use in instance methods?

Chapter Review-Privacy n What types of instance variables do you not need to worry about when returning? n Why is returning a private instance object sometimes a bad thing to do in a method?

Chapter review-Packages n What are packages? n What statement would we use to have access to the package edu.cs103.stuff? n What statement would we use in our class files to make it part of package edu.cs103.stuff?