Introduction To Scientific Programming Chapter 5 – More About Objects and Methods.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 7: User-Defined Functions II
Java Software Solutions
Road Map Introduction to object oriented programming. Classes
Chapter 51 Feb 08, Chapter 52  Methods in a class are invoked using objects A a1 = new A(); a1.func1();  Calling object and the dot can be omitted.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
More About Objects and Methods
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.
Constructors. Defining Constructors  A constructor is a special kind of method that is designed to perform initializations, such as giving values to.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Writing Classes (Chapter 4)
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
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.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
More About Objects and Methods Chapter 5. When an Object Is Required Methods called outside the object definition require an object to precede the method.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Lecturer: Dr. AJ Bieszczad Chapter 5 COMP 150: Introduction to Object-Oriented Programming 5-1 l Programming with Methods l Static Methods and Static Variables.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
10-Nov-15 Java Object Oriented Programming What is it?
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Programs and Classes A program is made up from classes Classes may be grouped into packages A class has two parts static parts exist independently Non-static.
CSC 142 Computer Science II Zhen Jiang West Chester University
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Classes, Interfaces and Packages
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 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
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.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
More About Objects and Methods
Topic: Classes and Objects
More About Objects and Methods
Static and non-Static Chapter 5.
CSC240 Computer Science III
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 6 Methods: A Deeper Look
More About Objects and Methods
Tonga Institute of Higher Education
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
Object Oriented Programming in java
Java Programming Language
Classes, Objects and Methods
More About Objects and Methods Chapter 5 Programming with Methods
Chapter 7 Objects and Classes
More About Objects and Methods Chapter 5 Programming with Methods
Presentation transcript:

Introduction To Scientific Programming Chapter 5 – More About Objects and Methods

S.Horton/107/Ch. 5Slide 2 Overview – More, More, More ! I.More on Methods A.Referencing B.Static Methods (and Variables) C.Overloading II.More on Classes A.Wrapper Classes B.Constructors C.Groups of Classes - Packages III.More on Software Design A.Top-Down Design B.Using Methods: Main/Helper/Class Interface

S.Horton/107/Ch. 5Slide 3 I. More On Methods - Referencing What are the possibilities? Reference a method outside of its’ class Reference a method from inside its’ class Also must consider lifetime: Reference a method before a class object has been created Reference a method after a class object has been created

S.Horton/107/Ch. 5Slide 4 Public methods called outside and after an object definition has occurred simply require the object name to precede the method name. For example: //Define object myOracle Oracle myOracle = new Oracle();... //dialog is a method defined in Oracle class myOracle.dialog();... When an Object Name Is Required

S.Horton/107/Ch. 5Slide 5 When An Object Name Is Not Required What if you want to use another method within the same class? You would need objectName, but it doesn’t exist yet. Answer: this. refers to the object that contains the current reference. Essentially, this. stands in for the object name. You may either use this., or omit it, since it is presumed – i.e. methods called within an class definition file do not need to reference itself.

S.Horton/107/Ch. 5Slide 6 Class Method Reference Example public class AddressBook { private final int MAX_ENTRIES = 100;//Fixed size limit of 100 private String BookName; private int numberOfEntries; … // // Method to find and display an entry in address book. // public boolean emptyBook() { if (this.numberOfEntries == 0) then //this. is optional return true; else return false; } // // Method that copies contents of AddressBook object // public void makeEqual(AddressBook otherObject) { otherObject.BookName = this.BookName; otherObject.numberOfEntries = this.numberOfEntries; otherObject.updateDate = this.updateDate; for (int i=1; i<this.numberOfEntries; i++) { If !(emptybook) then //this. not used, o.k.! … }

S.Horton/107/Ch. 5Slide 7 I.-B. Static Methods You’ve thought/seen that some methods don't need an object to do their job: Ex. a method to calculate the area of a circle of radius r You should just pass the required parameter and return the area! This is accomplished by using a static method. These methods are also called class methods. Use the className that contains the method instead of an objectName to invoke it. Ex. Math.pow(x,3) Declare static methods with the static modifier. Ex: public static double area(double radius)...

S.Horton/107/Ch. 5Slide 8 Uses for Static Methods Static methods are commonly used to provide libraries of useful and related methods. It is good practice to group static methods together, when possible. Examples: the Math class provided with Java methods include pow, sqrt, max, min, etc. the SavitchIn class for console Input not automatically provided with Java methods include readLineInt, readLineDouble, etc.

S.Horton/107/Ch. 5Slide 9 The Matrix – Method Invocation StaticNon-Static Within A Class methodNamethis.methodName * Outside Class ClassName.methodNameobjectName.methodName

S.Horton/107/Ch. 5Slide 10 Watch out! A static method cannot reference an instance variable from it’s class Likewise, a static method cannot automatically reference a non-static method from its or any other class. The only exception to above is if the static method creates an object of the class to use as a calling object. Reconciling Static Methods and Method References

S.Horton/107/Ch. 5Slide 11 Static Variables By default, variables are dynamic. However, you can also create static variables with the reserved word static : static int numberOfInvocations = 0; May be public or private but are usually private for the same reasons instance variables are (encapsulation). private static int numberOfInvocations = 0; There is only one copy of a static variable and it can be accessed by any object of the class. Can be used to let objects of the same class coordinate.

S.Horton/107/Ch. 5Slide 12 Static Variables - II Static variables defined at the class level are called Class variables. If the variable is public, it can be referenced outside of the class by ClassName.variableName Ex. Math.PI A public static variable at the program class level has visibility throughout the program – i.e. a global variable.

S.Horton/107/Ch. 5Slide 13 Definition: Privacy Leaks Anytime you return an object from a method, you are giving back an address, not a value the object is "unprotected" (usually undesirable) The object looses it’s privacy – privacy leak This applies to any class object (custom, wrapper, etc..) One solution is to stick to returning primitive types ( int, char, double, boolean, etc. Best solution is called cloning … temp = passedObject.clone(); // method that clones (copies) object return temp; }

S.Horton/107/Ch. 5Slide 14 I.-C. Overloading You can have the same method name with more than one definition within the same class! Why do this? Same calculations, different data types Same object, different initialization conditions Each definition must have a different “signature” This means the same name but different argument types, or a different number of arguments, or a different ordering of argument types. The return type is not part of the signature and cannot be used to distinguish between two methods.

S.Horton/107/Ch. 5Slide 15 Signature A method signature is the combination of method name and number and types of arguments, in order:.equals(int) has a different signature than. equals(String) (same method name, different argument types) myMethod(1) has a different signature than myMethod(1, 2) same method name, different number of arguments myMethod(1,1.2) different signature than myMethod(1.2,1) (same method name and number of arguments, but different order of argument types.)

S.Horton/107/Ch. 5Slide 16 Method Overloading Example static double max(double a, double b) Returns the greater of two double values.max static float max(float a, float b) Returns the greater of two float values.max static int max(int a, int b) Returns the greater of two int values.max static long max(long a, long b) Returns the greater of two long values.max

S.Horton/107/Ch. 5Slide 17 It’s a Complicated World – Potential Issues with Overloading If you accidentally use the wrong data type as an argument, you can invoke a different method. If Java does not find a signature match, it attempts some automatic type conversions, e.g. int to double. Hence, an unwanted version of the method may execute. Finally, you cannot have two methods that only differ in return type. This will produce an error: public double getWeight(); public float getWeight();

S.Horton/107/Ch. 5Slide 18 II. More On Classes - Wrapper Classes Used to wrap primitive types in a class structure All primitive types have an equivalent class The class includes useful constants and static methods (including conversion back to primitive type)

S.Horton/107/Ch. 5Slide 19 Wrapper class example - Integer Declare an Integer class variable: Integer n = new Integer(); Convert the value of an Integer variable to its primitive type, int : int i = n.intValue(); //intValue returns an int Some useful Integer methods/constants: Integer.MAX_VALUE,Integer.MIN_VALUE - maximum and minimum integer value the computer can represent Integer.valueOf("123"),Integer.toString(123) to convert a string to an integer and visa versa

S.Horton/107/Ch. 5Slide 20 Usage of Wrapper Classes Wrapper Class variables contain address of value variable declaration example: Integer n; variable declaration & init: Integer n = new Integer(0); assignment: n = new Integer(5); Primitive Type variables contain the value variable declaration example: int n; variable declaration & init.: int n = 0; assignment: n = 99; There are some important differences in the code using wrapper classes versus primitive types

S.Horton/107/Ch. 5Slide 21 II.-B. Constructors A constructor is a special method designed to initialize instance variables Automatically called when an object is created using new: Integer n = new Integer(0); Often overloaded - more than one per class! You may have different versions to initialize all, some, or none of the instance variables Each constructor has a different signature (a different number or sequence of argument types)

S.Horton/107/Ch. 5Slide 22 Defining Constructors Constructor headings have the same name as the class and do not include any reference to a return type or void. A constructor with no parameters is called a default constructor. If no constructor is provided, Java automatically creates a default constructor. If any constructor is provided, then no constructors are automatically created by the compiler

S.Horton/107/Ch. 5Slide 23 Constructor Programming Suggestions In your custom Classes, include a constructor that initializes all instance variables. Also, include a constructor that has no parameters (default constructor) This overrides any automatic action by the compiler Include overloaded versions of constructor to handle different initializations Important note: you cannot call a constructor for an object after it is created If you want to change values of instance variables after you have created an object, you should create a set method!

S.Horton/107/Ch. 5Slide 24 Constructor Example - PetRecord public class PetRecord { private String name; private int age; //in years private double weight; //in pounds... public PetRecord(String initialName) { name = initialName; age = 0; weight = 0; } Initializes three instance variables: name from the parameter and age and weight with default initial values. Sample use: PetRecord pet1 = new Pet("Eric");

S.Horton/107/Ch. 5Slide 25 … public PetRecord(String initialName, int initialAge, double initialWeight) { set(initialName, initialAge, initialWeight); } … private void set(String initialName, int initialAge, double initialWeight) { name = initialName; if ((initialAge < 0) || (initialWeight < 0)) { System.out.println(“Error: …”); } else { age = initialAge; weight = initialWeight; } You Can Use Other Methods in a Constructor

S.Horton/107/Ch. 5Slide 26 II.-C. Packages A package is a way to group a collection of related classes Think of a package as a library of classes They do not have to be in the same directory as your program The first line of each class in the package must be the keyword package followed by the name of the package: package mystuff.utilities; To use classes from a package in a program put an import statement at the start of the file: import mystuff.utilities.*; //all classes in directory

S.Horton/107/Ch. 5Slide 27 A Package Name myjava general utilities AClass.java AnotherClass.java Classes in the package myjava is the base path myjava.general.utilities is a specific package name

S.Horton/107/Ch. 5Slide 28 Package Naming Conventions Use lowercase The package name is the pathname with subdirectory separators ("/") replaced by dots For example, if the package is in a directory named "utilities" in directory "mystuff", the package name is: imports myjava.general.utilities; imports myjava.general.*; imports myjava.*;

S.Horton/107/Ch. 5Slide 29 Adding A Custom Package Path To JCreator

S.Horton/107/Ch. 5Slide 30 III. Software Design – “Top-Down” Program Design Step 1: Define potential objects and formulas needed Step 2: Write a list of tasks, in pseudocode, that the program must do. Step 3: Create a flow diagram Step 4: For each task in the program, write a list of subtasks, in pseudocode, that the method must do. Step 5: If you can easily write Java statements for any subtask, you are finished with that subtask. Step 6: Repeat Steps 4. & 5. until done.

S.Horton/107/Ch. 5Slide 31 Program Design Example – “Lab 3 Investment Account” Step 1: Define Class InvestmentAccount w/ attributes of a savings account: balance, interest rate, deposit, contributions… Methods include open, deposit, add interest, close, … Step 2: Program Greeting Open investment account #1 w/ deposit Open investment account #2 w/ deposit Run investment strategy #1 & compute rate of return Compute difference and declare the superior strategy

S.Horton/107/Ch. 5Slide 32 Lab 3 Investment Account – Step 3

S.Horton/107/Ch. 5Slide 33 Lab 3 Investment Account – Step 4 Step 4: … Open Investment Account #1 by instantiating an InvestmentAccount object with an account name, account number, initial deposit, … … Open Investment Account #2 by instantiating an InvestmentAccount object with an account name, account number, initial deposit, … … For investment strategy #1: for each of the 12 cycles, add $500 to account and compute new balance with interest …

S.Horton/107/Ch. 5Slide 34 Programming Tip: Put A main In All Classes! A main method can be used to test all members of any class. It serves as test or “driver” code that can be left in a class and added to as you go. If you change the name of your project/program to the name of just your custom class, it will execute the classes’ main method. Otherwise, when the class is used to create objects, the main method is ignored.

S.Horton/107/Ch. 5Slide 35 Diagnostic main Main methods in Classes are referred to as diagnostic main methods. Remember: Because main must be static, you can't automatically invoke non-static methods of the class. You can however, invoke a non-static method in main if you create an object of the class.

S.Horton/107/Ch. 5Slide 36 Summary – Further Additions To A Class Diagnostic main methods. set… method to change an instance variable (complement of get… method) equals method to define equivalent objects clone method to copy your object to a new object Also, don’t forget writeOutput or toString to display contents of an object.