30
Java Programming Java Programming Chapter 3 Chapter 3 More about classes More about classes

Java Programming

Embed Size (px)

DESCRIPTION

Java Programming. Chapter 3 More about classes. Why?. To make classes easier to find and to use to avoid naming conflicts to control access programmers bundle groups of related classes and interfaces into packages. Official Definition. - PowerPoint PPT Presentation

Citation preview

Java ProgrammingJava Programming

Chapter 3Chapter 3

More about classesMore about classes

Why?Why?

To make classes easier to find and to useTo make classes easier to find and to use to avoid naming conflicts to avoid naming conflicts to control access to control access programmers bundle groups of related programmers bundle groups of related

classes and interfaces into packages. classes and interfaces into packages.

Official DefinitionOfficial Definition

A A packagepackage is a collection of related classes is a collection of related classes and interfaces providing access protection and interfaces providing access protection and namespace management and namespace management

Where?Where?

The classes and interfaces that are part of The classes and interfaces that are part of the Java platform are members of various the Java platform are members of various packages that bundle classes by function:packages that bundle classes by function:

fundamental classes are in java.lang, fundamental classes are in java.lang, classes for reading and writing (input and classes for reading and writing (input and output) are in java.io, and so on. output) are in java.io, and so on.

You can put your classes and interfaces in You can put your classes and interfaces in packages, too. packages, too.

ExampleExample

Suppose that you write a group of classes Suppose that you write a group of classes that represent a collection of graphic that represent a collection of graphic objects, such as circles, rectangles, lines, objects, such as circles, rectangles, lines, and points. and points.

You also write an interface, Draggable, that You also write an interface, Draggable, that classes implement if they can be dragged classes implement if they can be dragged with the mouse by the user: with the mouse by the user:

////in the Graphic.java filein the Graphic.java file

public class Graphic { . . . } public class Graphic { . . . }

////in the Circle.java filein the Circle.java file

public class Circle extends Graphic public class Circle extends Graphic implements Draggable { . . . } implements Draggable { . . . }

////in the Rectangle.java filein the Rectangle.java file

public class Rectangle extends Graphic public class Rectangle extends Graphic implements Draggable { . . . } implements Draggable { . . . }

////in the Draggable.java filein the Draggable.java file

public interface Draggable { . . . } public interface Draggable { . . . }

Why Bundle in a PackageWhy Bundle in a Package

You and other programmers can easily determine that You and other programmers can easily determine that these classes and interfaces are related. these classes and interfaces are related.

You and other programmers know where to find classes You and other programmers know where to find classes and interfaces that provide graphics-related functions. and interfaces that provide graphics-related functions.

The names of your classes won’t conflict with class names The names of your classes won’t conflict with class names in other packages, because the package creates a new in other packages, because the package creates a new namespace. namespace.

You can allow classes within the package to have You can allow classes within the package to have unrestricted access to one another yet still restrict access unrestricted access to one another yet still restrict access for classes outside the package. for classes outside the package.

Creating a PackageCreating a Package

you put a class or an interface in it. you put a class or an interface in it. To do this, you put a package statement at To do this, you put a package statement at

the top of the source file in which the class the top of the source file in which the class or the interface is defined. or the interface is defined.

For example, the following code appears in For example, the following code appears in the source file Circle.java and puts the the source file Circle.java and puts the Circle class in the graphics package: Circle class in the graphics package:

package graphics; package graphics;

public class Circle extends Graphic implements public class Circle extends Graphic implements Draggable Draggable

{ {

. . . . . .

} }

The Circle class is a public member of the graphics The Circle class is a public member of the graphics package. package.

You must include a package statement at the top of You must include a package statement at the top of every source file that defines a class or an interface every source file that defines a class or an interface that is to be a member of the graphics package. that is to be a member of the graphics package.

So you would also include the statement in Rectangle.java So you would also include the statement in Rectangle.java and so on:and so on:

package graphics; package graphics; public class Rectangle extends Graphic implements public class Rectangle extends Graphic implements

Draggable Draggable { . . . } { . . . } The scope of the package statement is the entire source The scope of the package statement is the entire source

file, so all classes and interfaces defined in Circle.java and file, so all classes and interfaces defined in Circle.java and Rectangle.java are also members of the graphics package. Rectangle.java are also members of the graphics package.

If you put multiple classes in a single source file, only one If you put multiple classes in a single source file, only one may be public, and it must share the name of the source may be public, and it must share the name of the source files base name. files base name.

Only public package members are accessible from outside Only public package members are accessible from outside the package. the package.

If you do not use a package statement, your If you do not use a package statement, your class or interface ends up in the class or interface ends up in the default default packagepackage, which is a package that has no , which is a package that has no name. name.

the default package is only for small or the default package is only for small or temporary applications or when you are just temporary applications or when you are just beginning development. beginning development.

Otherwise, classes and interfaces belong in Otherwise, classes and interfaces belong in named packages. named packages.

Naming a PackageNaming a Package

With programmers all over the world writing classes and With programmers all over the world writing classes and interfaces using the Java programming language, it is likely interfaces using the Java programming language, it is likely that two programmers will use the same name for two that two programmers will use the same name for two different classes. different classes.

The previous example does just that: It defines a Rectangle The previous example does just that: It defines a Rectangle class when there is already a Rectangle class in the java.awt class when there is already a Rectangle class in the java.awt package. package.

Yet the compiler allows both classes to have the same name. Yet the compiler allows both classes to have the same name. Why? Why?

Because they are in different packages, and the fully qualified Because they are in different packages, and the fully qualified name of each class includes the package name. name of each class includes the package name.

That is, the fully qualified name of the Rectangle class in the That is, the fully qualified name of the Rectangle class in the graphics package is graphics.Rectangle, and the fully graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package qualified name of the Rectangle class in the java.awt package is java.awt.Rectangle. is java.awt.Rectangle.

Using Package MembersUsing Package Members

Only public package members are accessible Only public package members are accessible outside the package in which they are defined. outside the package in which they are defined.

To use a public package member from outside its To use a public package member from outside its package, you must do one or more of the package, you must do one or more of the following: following: – Refer to the member by its long (qualified) name Refer to the member by its long (qualified) name – Import the package member Import the package member – Import the member's entire package Import the member's entire package – Each is appropriate for different situations, as explained Each is appropriate for different situations, as explained

in the following sections. in the following sections.

Refer to a Package my nameRefer to a Package my name

so far we’ve used simple names – for classes – so far we’ve used simple names – for classes – RectangleRectangle

you can use the simple name if its within the same you can use the simple name if its within the same package as that member – or if you have imported package as that member – or if you have imported that packagethat package

But – if you want to use a package that has not been But – if you want to use a package that has not been importedimported

graphics.Rectangle -- qualified name graphics.Rectangle -- qualified name You could use it to :You could use it to :graphics.Rectangle myRect = new graphics.Rectangle()graphics.Rectangle myRect = new graphics.Rectangle()

Importing a package memberImporting a package member

import graphics.Circle; import graphics.Circle;

Now you can refer to the Circle class by its Now you can refer to the Circle class by its simple name: simple name:

Circle myCircle = new Circle(); Circle myCircle = new Circle();

Importing an entire packageImporting an entire package

To import all the classes and interfaces To import all the classes and interfaces contained in a particular package, use the contained in a particular package, use the import statement with the asterisk (*) import statement with the asterisk (*) wildcard character: wildcard character:

import graphics.*; import graphics.*; Now you can refer to any class or interface Now you can refer to any class or interface

in the graphics package by its short name:in the graphics package by its short name:Circle myCircle = new Circle(); Circle myCircle = new Circle(); Rectangle myRectangle = new Rectangle(); Rectangle myRectangle = new Rectangle();

JRSJRS

For your convenience, the Java runtime For your convenience, the Java runtime system automatically imports three entire system automatically imports three entire packages: packages: – The default package (the package with no The default package (the package with no

name) name) – The java.lang package The java.lang package – The current package by default The current package by default

Class VariablesClass Variables

class variables are attributes common to all class variables are attributes common to all objects belonging to a certain classobjects belonging to a certain class

These are also called static variablesThese are also called static variables static does not mean unchangeablestatic does not mean unchangeable class variables declared staticclass variables declared static exp – a variable that keeps a check on how exp – a variable that keeps a check on how

many instances of a particular class there many instances of a particular class there are at one timeare at one time

Bank AccountBank Account

every bank account – a particular balanceevery bank account – a particular balance a particular account holdera particular account holder these data need to be available in one these data need to be available in one

instance for each account – ordinary instance for each account – ordinary instance variablesinstance variables

Interest rate – class variableInterest rate – class variable Since all accounts will have the same Since all accounts will have the same

interest rate – inefficient to store this in interest rate – inefficient to store this in every single accountevery single account

public class Account {public class Account {

//class variables//class variables

private static double interestRate;private static double interestRate;

//class methods//class methods

public static double getInterest ( ){public static double getInterest ( ){

interestRate = newInterest;interestRate = newInterest;

}}

//instance variables//instance variables

private int customerNo;private int customerNo;

private double balance, interestEarned;private double balance, interestEarned;

//constructor//constructorpublic Account (int customer){public Account (int customer){

customerNo = customer;customerNo = customer;}}//instance methods//instance methodspublic double getBalance() {public double getBalance() {

return balance;return balance;}}public void transaction(double amount){public void transaction(double amount){

//negative amount => withdrawal//negative amount => withdrawalif (amount < 0 && balance + amount < 0)if (amount < 0 && balance + amount < 0) System.out.println (“Withdrawal cannot be done”);System.out.println (“Withdrawal cannot be done”);elseelse

balance = balance + amount;balance = balance + amount;}}

public void getDailyInterest(){public void getDailyInterest(){

interestEarned = interestEarned + balance * interestEarned = interestEarned + balance * interestRate/100/365;interestRate/100/365;

}}

public void addInterest(){public void addInterest(){

balance = balance+interestEarned;balance = balance+interestEarned;

interestEarned = 0;interestEarned = 0;

}}

}}

Every account has three class variablesEvery account has three class variables– keep track of customer numberskeep track of customer numbers– current balancecurrent balance– interest earned during the yearinterest earned during the year

constructor initializes a new account, a unique customer constructor initializes a new account, a unique customer number is provided as an argument to the constructornumber is provided as an argument to the constructor

instance variables balance and interestEarned default to 0instance variables balance and interestEarned default to 0 getBalance is called – checks balance of accountgetBalance is called – checks balance of account transaction – called each time a deposit or withdrawal is transaction – called each time a deposit or withdrawal is

mademade getDailyInterest – called once a day – it calculates the getDailyInterest – called once a day – it calculates the

interest earnedinterest earned addInterest – called end of every yearaddInterest – called end of every year

class variable – interestRateclass variable – interestRate

use staticuse static

class methodsclass methods

getInterest – setInterest – read and change the getInterest – setInterest – read and change the interest rateinterest rate

class variables and class methods can have class variables and class methods can have modifiers – public, private …modifiers – public, private …

instance methods can have access to the class instance methods can have access to the class variables and methods – read and changevariables and methods – read and change

if class variable is changed in an instance if class variable is changed in an instance method, the change will affect all the objects method, the change will affect all the objects since they all share same classsince they all share same class

a class variable is initialized when the class is a class variable is initialized when the class is used for the first time in a programused for the first time in a program

can initialize to a specific valuecan initialize to a specific value

will default to zero of notwill default to zero of not

Constructors are not used to initialize class Constructors are not used to initialize class variablesvariables

constructors only initialize the variables dealing constructors only initialize the variables dealing with a particular instance of the classwith a particular instance of the class

class variables are used to define constants – class variables are used to define constants – finalfinal

Recap:Recap:

class variables are declared – staticclass variables are declared – static

exist only in one edition – common to all objects exist only in one edition – common to all objects belonging to the classbelonging to the class

are initialized when class is loadedare initialized when class is loaded

exist for the remainder of the programexist for the remainder of the program

can be initialized if necessary in a special class can be initialized if necessary in a special class initializerinitializer

are often used to define constantsare often used to define constants

Class MethodsClass Methods

methods marked with staticmethods marked with static getInterest and setInterestgetInterest and setInterest they do not handle individual accountsthey do not handle individual accounts they use only class variables no instance they use only class variables no instance

variablesvariables if you try – compile will failif you try – compile will fail

Call StatementsCall Statements

Account.setInterest(4.5);Account.setInterest(4.5); double ir = Account.getInterest();double ir = Account.getInterest(); also same as instance methodsalso same as instance methods Account acc = new Account(1234);Account acc = new Account(1234); acc.setInterest(5.1); but setInterest does not acc.setInterest(5.1); but setInterest does not

read or change object acc – it changes read or change object acc – it changes something that affects all the objects of the something that affects all the objects of the classclass

And FinallyAnd Finally

Not unusual to have a class with all class Not unusual to have a class with all class methodsmethods

used to encapsulate the methodsused to encapsulate the methods See class Math – pg 3.5See class Math – pg 3.5