More About Objects and Methods Chapter 5 Programming with 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.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
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.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
More About Objects and Methods
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.
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.
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.
Classes, Objects, and Methods
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Introduction To Scientific Programming Chapter 5 – More About Objects and Methods.
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.
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.
COMP 110 Constructors Luv Kohli October 13, 2008 MWF 2-2:50 pm Sitterson 014.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Catie Welsh March 23,  Lab 6 due Friday by 1pm 2.
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.
Classes - Intermediate
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS180 Recitation Chapter 7: Defining Your Own Classes II.
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
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 5: Enhancing Classes
User-Written Functions
Chapter 7 User-Defined Methods.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
3 Introduction to Classes and Objects.
Java Primer 1: Types, Classes and Operators
More About Objects and Methods
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Static and non-Static Chapter 5.
CSC240 Computer Science III
Inheritance Basics Programming with Inheritance
Corresponds with Chapter 7
Classes, Objects, and Methods
Defining Classes and Methods
Computer Programming with JAVA
More About Objects and Methods
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 4 Defining Classes I
Object Oriented Programming in java
Announcements Lab 5 was due today Program 3 due Monday by 12pm
Classes, Objects and Methods
More About Objects and Methods Chapter 5 Programming with Methods
Chapter 7 Objects and Classes
Presentation transcript:

More About Objects and Methods Chapter 5 Programming with Methods Static Methods and Static Variables Designing Methods Constructors Packages

Announcements/Reminders Exam 1 Returned next week in recitation Will go over solution today Project 3: due Thursday, Feb. 17 at 10:30 pm. (2 weeks b/c of test)

Null Pointer Exception If the compiler requires you to initialize an object (class variable), you can set it to null if you have no other initial value. You can use == and != to see if a class variable is equal to null, because null is used like an address. Gotcha: Null Pointer Exception If you invoke a method using a variable that is initialized to null, you will get an error message that says "Null Pointer Exception". Species specialSpecies = null; specialSpecies.readInput(); Null Pointer Exception Species specialSpecies = new Species(); specialSpecies.readInput(); OK

null example ERROR: Species a; Species b = new Species(); . . . if (a == b) . . . BETTER: Species a = null;

Static Methods Some methods do not need an object to do their job For example, methods to calculate area: just pass the required parameters and return the area Use the class name instead of an object name to invoke them For example CircleFirstTry is a class with methods to perform calculations on circles: CircleFirstTry.area(myRadius); Notice that the the method invocation uses "className." instead of " circleObject." Also called class methods

Static Methods Declare static methods with the static modifier, for example: public static double area(double radius) ... Since a static method does not need a calling object, it cannot refer to a (nonstatic) instance variable of the class. Likewise, a static method cannot call a nonstatic method of the class (unless it creates an object of the class to use as a calling object).

Uses for Static Methods Static methods are commonly used to provide libraries of useful and related methods Examples: the Math class automatically provided with Java methods include pow, sqrt, max, min, etc. see later slide for more details SavitchIn defines methods for keyboard input not automatically provided with Java methods include readLineInt, readLineDouble, etc. see the appendix

Overloading The same method name has more than one definition within the same class Each definition must have a different signature different argument types, 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 with the same name and parameter types

Signature the combination of method name and number and types of arguments, in order equals(Species) 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(10, 1.2) has a different signature than myMethod(1.2, 10) same method name and number of arguments, but different order of argument types

Signatures Public void set(String newName) signature: set(String) Public int set(double newWeight) signature: set(double) Public double set(double newWeight, String newName) signature: set(double,String) Remember: return type is not included

Gotcha: You Cannot Overload Based on the Returned Type Compiler will not allow two methods with same name, same types and number of parameters, but different return types in the same class: In a situation like this you would have to change the name of one method or change the number or types of parameters. public double getWeight() Can't have both in the same class public char getWeight()

Overloading: Example public class Pet { private String name; private int age; private double weight; public void set(String newName) . . . public void set(int newAge) . . . public void set(double newWeight) . . . . . .

Overloading Example Pet animal = new Pet(); . . . animal.set(“Jackie”); //set name animal.set(5); //set age animal.set(25.0); //set weight

Overloading Example public void set(String newName, int newAge, double newWeight) animal.set(“Jackie”, 5, 25.0); Be careful: animal.set(“Jackie”, 25.0, 5); will be allowed – but will not do what you want

Constructors A constructor is a special method designed to initialize instance variables Automatically called when an object is created using new Has the same name as the class Often overloaded (more than one constructor for the same class definition) 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)

Defining Constructors Constructor headings do not include the word void. In fact, constructor headings do not include a return type at all. 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 created automatically. Programming Tip Include a constructor that initializes all instance variables. Include a constructor that has no parameters. Include your own default constructor.

Constructor Example public class Pet { private String name; private int age; //in years private double weight; //in pounds . . . public Pet(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: Pet pet1 = new Pet("Eric");

Using Constructors Always use a constructor after new For example, using the Pet class in text: Pet myCat = new Pet("Calvin", 5, 10.5); this calls the Pet constructor with String, int, double parameters If you want to change values of instance variables after you have created an object, you must use other methods for the object you cannot call a constructor for an object after it is created set (mutator) methods should be provided for this purpose

Programming Tip: You Can Use Other Methods in a Constructor public Pet(String initialName, int initialAge, double initialWeight) { name = initialName; if ((initialAge < 0) || (initialWeight < 0)) System.out.println("Error…"); } else age = initialAge; weight = initialWeight; avoids possible confusion about set parameters less method invocation overhead shorter possibly more consistent with other constructors and methods public Pet(String initialName, int initialAge, double initialWeight) { set(initialName, initialAge, initialWeight); } Use the one your instructor or supervisor prefers.

Default Constructor Constructor run when use: Classtype objectName = new Classtype(); Takes no arguments You have used: String myName = new String();

Default Constructor: Example public class Student { private int studentNumber; private String studentName; private double studentAge; public Student() studentNumber = 0; studentName=“No name entered”; studentAge = 0; } . . .

Default Constructor: Example Student number1 = new Student(); Calls default constructor for class student and will set the variables as in the default constructor: studentNumber = 0; studentName=“No name entered”; studentAge = 0;

Packages A way of grouping and naming a collection of related classes they serve 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.*; note the ".*" notation

Package Naming Conventions Use lowercase The name is the pathname with subdirectory separators ("\" or "/", depending on your system) replaced by dots For example, if the package is in a directory named "utilities" in directory "mystuff", the package name is: mystuff.utilities

Package Naming Conventions Pathnames are usually relative and use the CLASSPATH environment variable For example, if: CLASSPATH=c:\javastuff\libraries, and your directory utilities is in c:\javastuff\libraries, then you would use the name: utilities the system would look in directory c:\javastuff\libraries and find the utilities package

Summary Part 1 A method definition can use a call to another method of the same class static methods can be invoked using the class name or an object name Top-down design method simplifies program development by breaking a task into smaller pieces Test every method in a program in which it is the only untested method

Summary Part 2 Each primitive type has a corresponding wrapper class Overloading: a method has more than one definition in the same class (but the number of arguments or the sequence of their data types is different) one form of polymorphism Constructor: a method called when an object is created (using new) default constructor: a constructor with no parameters