static. big java by cay horstmann copyright © 2009 by john wiley & sons. all rights reserved. a...

39
Static

Upload: kerry-powers

Post on 02-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Static

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• A static method does not operate on an object

double dY = 4;double dY = matObject.sqrt(); // Error

double dY = Math.sqrt(9); //correct

• Static methods are declared inside classes

• Naming convention: Classes start with an uppercase letter; objects start with a lowercase letter:

MathSystem.out

Calling Static Methods

Implicit versus Explicit Parameters

• The implicit parameter is the object reference, whereas the explicit parameter(s) are/is the argument(s) to the method.

• strName.indexOf(cSpace);• Math.pow(2,3); //no implicit param -- static• Most often, when we refer to parameters, we

mean the explicit parameters.

• Example:

public class Metric{ public static double getKilograms(double dPounds){

return dPounds * 0.454; } // More methods can be added here.}

• Call with class name instead of object:

double dKilos = Metric. getKilograms(150);

Static Methods

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Syntax 4.3 Static Method Call

Suppose Java had no static methods. How would you use the Math.sqrt method for computing the square root of a number x?

Answer:

Math mat = new Math();double dResult = mat.sqrt(x);//note that Math methods ARE STATIC

Suppose the methods of java.util.Random were static, how would you call them?

Answer:

int nResult = Random.nextInt(20); //int betweeen 0-19 //note that Random methods ARE NON-STATIC

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

• A classs need not be exclusively static or non-static, it can be both.

Static Variables

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• A static variable belongs to the class, not to any object of the class:

public class BankAccount { ... private double balance; private int accountNumber; private static int lastAssignedNumber = 1000; }

• If lastAssignedNumber was not static, each instance of BankAccount would have its own value of lastAssignedNumber

Static Variables

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• public BankAccount() { // Generates next account number to be assigned lastAssignedNumber++; // Updates the static variable accountNumber = lastAssignedNumber;

// Sets the instance variable } /this no-args constructor create a serial number the bank account

Static Variables

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

A Static Variable and Instance Variables

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Exception: Static constants, which may be either private or public: public class BankAccount { ... public static final double OVERDRAFT_FEE = 5;

// Refer to it as BankAccount.OVERDRAFT_FEE }

//in the above case, OVERDRAFT_FEE is a constant

Static Variables

Class Objects

Harry tells you that he has found a great way to avoid those pesky objects: Put all code into a single class and declare all methods and variables static. Then main can call the other static methods, and all of them can access the static variables. Will Harry’s plan work? Is it a good idea?

Answer: Yes, it works. Static methods can access static variables of the same class. But it is a terrible idea. As your programming tasks get more complex, you will want to use objects and classes to organize your programs.

Use static appropriately and parsimoniously.

Self Check 8.15

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Constants

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Syntax 4.1 Constant Definition

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• A final variable is a constant

• Once its value has been set, it cannot be changed

• Named constants make programs easier to read and maintain

• Convention: Use all-uppercase names for constants

final double QUARTER_VALUE = 0.25; final double DIME_VALUE = 0.1; final double NICKEL_VALUE = 0.05; final double PENNY_VALUE = 0.01;

payment = dollars + quarters * QUARTER_VALUE + dimes * DIME_VALUE + nickels * NICKEL_VALUE + pennies * PENNY_VALUE;

Constants: final

Packages

Packages

• Packages help organize your code• Packages disambiguate• Packages avoid naming conflicts• Using the fully qualified name of an object,

you need not import it (though it's best to import).

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

The API Documentation of the Standard Java Library

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Package: a collection of classes with a related purpose

• Import library classes by specifying the package and class name:

import java.awt.Rectangle;

• You don’t need to import classes in the java.lang package such as String and System

Packages

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Syntax 2.4 Importing a Class from a Package

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Package Purpose Sample Class

java.lang Language support Math

java.util Utilities Random

java.io Input and output PrintStream

java.awt Abstract Windowing Toolkit Color

java.applet Applets Applet

java.net Networking Socket

java.sql Database Access ResultSet

javax.swing Swing user interface JButton

omg.w3c.domDocument Object Model for XML

documentsDocument

Packages

• Package: Set of related classes

• Important packages in the Java library:

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• To put classes in a package, you must place a line

package packageName;

as the first instruction in the source file containing the classes

• Package name consists of one or more identifiers separated by periods

Organizing Related Classes into Packages

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Can always use class without importing:

java.util.Scanner in = new java.util.Scanner(System.in);

• Tedious to use fully qualified name

• Import lets you use shorter class name:

import java.util.Scanner; ... Scanner in = new Scanner(System.in)

• Can import all classes in a package:

import java.util.*;

• Never need to import java.lang

• You don’t need to import other classes in the same package

Importing Packages

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Use packages to avoid name clashes

java.util.Timer

vs.

javax.swing.Timer

• Package names should be unambiguous

• Recommendation: start with reversed domain name:

com.horstmann.bigjava

• edu.sjsu.cs.walters: for Britney Walters’ classes ([email protected])

• Path name should match package name:

com/horstmann/bigjava/Financial.java

Package Names

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Base directory: holds your program's Files

• Path name, relative to base directory, must match package name:

com/horstmann/bigjava/Financial.java

Package and Source Files

Which of the following are packages?

a. java

b. java.lang

c. java.util

d. java.lang.Math

Answer:

a.No

b.Yes

c.Yes

d.No

Self Check 8.18

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Is a Java program without import statements limited to using the default and java.lang packages?

Answer: No — you simply use fully qualified names for all other classes, such as java.util.Random and java.awt.Rectangle.

Self Check 8.19

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Gregorian Calendar Extra Credit

Asciify Example

Polymorphism: assingment to references

• An object (instantiated in memory) may be assigned to the following reference types:

• 1/ a reference type of the same type:– Double dubVal = new Double(91.5);

• 2/ any superclass reference, including abstract classes. i.e; any class in the upline of that object’s hierarchy.– Number numNum = new Double(9.15);– Object objNum = new Double(91.5);

Is-a; or to be or not to be.

• ...that is the question.• To check whether an instantiated object may

be stored in reference of another type, it must affirmatively answer this question: "Is object a referenceType?"

Upcasting/Downcasting

Polymorphism: assingment to references

• 3/ Any Interface that the object implementsComparable comNum = new Double(91.5);

Interfaces

• A class implements an interface rather than extends it. Any class that implements the interface must override all the interface methods with it's own methods.

• Interface names often end with "able" to imply that they add to the capabilty of the class.

• An interface is a contract; it defines the methods

Inheritence

• A class that extends a superclass inherets all the fields and methods of its superclass AND those of its entire class hierarchy.

• A superclass is more generic and contains less data. A subclass is more specific and contains more data.

• Access to members through get and set.

Interfaces

• A class implements an interface rather than extends it. Any class that implements the interface must override all the interface methods with it's own methods.

• Interface names often end with "able" to imply that they add to the capabilty of the class.

SprintRace Example

Poster Example