Anda di halaman 1dari 38

7

Creating Classes and Objects

Copyright © 2007, Oracle. All rights reserved.


Objectives

After completing this lesson, you should be able to do


the following:
• Define instance variables and methods
• Define the no-arg (default) constructor method
• Instantiate classes and call instance methods
• Perform encapsulation by using packages to
group related classes
• Control access with public and private access
modifiers
• Use class variables and methods

7-2 Copyright © 2007, Oracle. All rights reserved.


Java Classes

Methods Objects

Contained in a class Packages

Attributes Object
references

7-3 Copyright © 2007, Oracle. All rights reserved.


Comparing Classes and Objects

Movie
• An object is an
instance of a public void displayDetails()
class.
• Objects have public void setRating()
their own
memory. private String title;
• Class definitions
must be loaded private String rating;
to create
instances.
mov1 mov2
title: Gone with the Wind title: Last Action Hero
rating: PG rating: PG-13

7-4 Copyright © 2007, Oracle. All rights reserved.


Creating Objects

• Objects are typically created by using the new


operator:

ClassName objectRef = new ClassName();

• For example, to create two Movie objects:


Movie mov1 = new Movie("Gone ...");
Movie mov2 = new Movie("Last ...");

title: Gone with the Wind title: Last Action Hero


rating: PG rating: PG-13

7-5 Copyright © 2007, Oracle. All rights reserved.


new Operator

The new operator performs the following actions:


• Allocates and initializes memory for the new
object
• Calls a special initialization method in the class
(this method is called a constructor)
• Returns a reference to the new object
Movie mov1 = new Movie("Gone with…");

mov1 title: Gone with the Wind


(when instantiated) rating: PG

7-6 Copyright © 2007, Oracle. All rights reserved.


Primitive Variables and Object Variables

Primitive variables Object variables


hold a value. hold references.

int i; Movie mov1;


mov1
i 0
null

int j = 3; Movie mov1 = new Movie();

j 3 mov1
title: null
rating: null

7-7 Copyright © 2007, Oracle. All rights reserved.


null Reference

• A special null value can be assigned to an object


reference but not to a primitive.
• You can compare object references to null.
• You can remove the association to an object by
setting the object reference to null.
Movie mov1; //Declare object reference

if (mov1 == null) //Ref not initialized?
mov1 = new Movie(); //Create a Movie object

mov1 = null; //Forget the Movie object

7-8 Copyright © 2007, Oracle. All rights reserved.


Assigning References

Assigning one reference to another results in two


references to the same object:

Movie mov1 = new Movie("Gone...");


mov1

title: Gone with the Wind


Movie mov2 = mov1; rating: PG

mov2

7-9 Copyright © 2007, Oracle. All rights reserved.


Declaring Instance Variables

Instance variables are declared within the class but


outside the methods, instance, or static intializers.
public class Movie {
public String title;
public String rating;
public float getPrice(){
return price; mov1
} title: null
rating: null
}
mov2
Create movies: title: null
rating: null
Movie mov1 = new Movie();
Movie mov2 = new Movie();

7-10 Copyright © 2007, Oracle. All rights reserved.


Accessing public Instance Variables

public instance variables can be accessed by using


the dot operator:

public class Movie {


public String title;
public String rating;
… Movie mov1 = new Movie();
} mov1.title = "Gone ...";

if (mov1.title.equals("Gone ... ") )
mov1.rating = "PG";

7-11 Copyright © 2007, Oracle. All rights reserved.


Defining Methods

A method in Java is equivalent to a function or


subroutine in other languages.

modifier returnType methodName (argumentList) {


// method body

}

7-12 Copyright © 2007, Oracle. All rights reserved.


7-13 Copyright © 2007, Oracle. All rights reserved.
Calling a Method

Objects communicate by using messages:


• All methods are defined within a class and are not
defined globally as in traditional languages.
• When you call a method, it is always in the context
of a particular object.
– myPen.write( ): Object-oriented programming
– Write (myPen): Traditional structured
programming

7-14 Copyright © 2007, Oracle. All rights reserved.


Specifying Method Arguments: Examples

• Specify the number and type of arguments in the


method definition:
public void setRating(String newRating) {
rating = newRating;
}
• If the method takes no arguments, leave the
parentheses empty:
public void displayDetails() {
System.out.println("Title is " + title);
System.out.println("Rating is " + rating);
}

7-15 Copyright © 2007, Oracle. All rights reserved.


7-16 Copyright © 2007, Oracle. All rights reserved.
Returning a Value from a Method

• Use a return statement to exit a method and to


return a value from a method:
public class Movie {
private String rating;

public String getRating () {
return rating;
}
}

• If the return type is void, no return is needed.


• You can use a return without a value to terminate
a method with a void return type.

7-17 Copyright © 2007, Oracle. All rights reserved.


Calling Instance Methods

public class Movie {


private String title, rating;
public String getRating(){
return rating;
}
public void setRating(String newRating){
rating = newRating;
}
Movie mov1 = new Movie();
}
String r = mov1.getRating();
Use the dot if (r.equals("G")) …
operator:

7-18 Copyright © 2007, Oracle. All rights reserved.


Encapsulation in Java

• Instance variables should be var


declared as private.
aMethod
• Only instance methods can access
private instance variables.
• private decouples the interface
aMethod()
of the class from its internal operation.

Movie mov1 = new Movie();


String rating = mov1.getRating();
String r = mov1.rating; // error: private
...
if (rating.equals("G"))

7-19 Copyright © 2007, Oracle. All rights reserved.


Passing Primitives to Methods

When a primitive or object reference value is passed to


a method, a copy of the value is generated:

int num = 150; num


150
anObj.aMethod(num);
System.out.println("num: " + num);

public void aMethod(int arg) {


arg
if (arg < 0 || arg > 100) 150
arg = 0;
System.out.println("arg: " + arg);
}

7-20 Copyright © 2007, Oracle. All rights reserved.


Passing Object References to Methods

When an object reference is passed to a method, the


object is not copied but the pointer to the object is
copied:

Movie mov1 = mov1


new Movie("Gone…"); title: Gone with the Wind
rating: PG
mov1.setRating("PG");
anObj.aMethod(mov1);
ref2

public void aMethod(Movie ref2) {


ref2.setRating("R");
}

7-21 Copyright © 2007, Oracle. All rights reserved.


Class Variables

Class variables:
• Belong to a class and are common to all instances
of that class
• Are declared as static in class definitions
public class Movie {
private static double minPrice; // class var
private String title, rating; // inst vars

title
rating
minPrice title
rating
title
rating
Movie class variable Movie objects

7-22 Copyright © 2007, Oracle. All rights reserved.


Initializing Class Variables

• Class variables can be initialized at declaration.


• Initialization takes place when the class is loaded.
• Use a static initializer block for complex
initialization.
• All class variables are initialized implicitly to
default values depending on the data type.

public class Movie {


private static double minPrice = 1.29;
private String title, rating;
private int length = 0;

7-23 Copyright © 2007, Oracle. All rights reserved.


7-24 Copyright © 2007, Oracle. All rights reserved.
Class Methods

Class methods are:


• Shared by all instances
• Useful for manipulating class variables
• Declared as static
public static void increaseMinPrice(double inc) {
minPrice += inc;
}
A class method is called using the name of the class or
an object reference.
Movie.increaseMinPrice(.50);
mov1.increaseMinPrice(.50);

7-25 Copyright © 2007, Oracle. All rights reserved.


Guided Practice: Class Methods
or Instance Methods

public class Movie {

private static float price = 3.50f;


private String rating;

public static void setPrice(float newPrice) {
price = newPrice;
}
public String getRating() {
return rating;
} Movie.setPrice(3.98f);
} Movie mov1 = new Movie(…);
mov1.setPrice(3.98f);
String a = Movie.getRating();
Legal or not? String b = mov1.getRating();

7-26 Copyright © 2007, Oracle. All rights reserved.


Examples in Java

Examples of static methods and variables:


• main()
• Math.sqrt()
• System.out.println()

public class MyClass {

public static void main(String[] args) {


double num, root;

root = Math.sqrt(num);
System.out.println("Root is " + root);
} …

7-27 Copyright © 2007, Oracle. All rights reserved.


Java Packages

oe

Customer Order Util

OrderEntry OrderItem

7-28 Copyright © 2007, Oracle. All rights reserved.


Grouping Classes in a Package

• Include the package keyword followed by the


package name at the top of the Java source file.
Use the dot notation to show the package path.
• If you omit the package keyword, the compiler
places the class in a default “unnamed” package.
• Use the –d flag with the javac compiler to create
the package tree structure relative to the specified
directory.
• Running a main() method in a packaged class
requires that:
– The CLASSPATH contain the directory having
the root name of the package tree
– The class name be qualified by its
package name

7-29 Copyright © 2007, Oracle. All rights reserved.


Setting the CLASSPATH with Packages

The CLASSPATH includes the directory containing the


top level of the package tree:
Package name .class location

CLASSPATH
C:\>set CLASSPATH=E:\Curriculum\courses\java\les06

7-30 Copyright © 2007, Oracle. All rights reserved.


7-31 Copyright © 2007, Oracle. All rights reserved.
Access Modifiers

acmevideo acmetools

public

protected

default

private

7-32 Copyright © 2007, Oracle. All rights reserved.


7-33 Copyright © 2007, Oracle. All rights reserved.
Summary

In this lesson, you should have learned the following:


• A class definition specifies a template for building
objects with identical features, such as instance
variables and methods.
• An object is an instance of a particular class.
– Create an object by using new.
– Manipulate an object by using its public instance
methods.

7-34 Copyright © 2007, Oracle. All rights reserved.


Practice 7 Overview:
Creating Classes and Objects

This practice covers the following topics:


• Defining new classes
• Specifying the classes’ instance variables and
instance methods
• Creating Customer objects in main()
• Manipulating Customer objects by using public
instance methods

7-35 Copyright © 2007, Oracle. All rights reserved.


7-36 Copyright © 2007, Oracle. All rights reserved.
7-37 Copyright © 2007, Oracle. All rights reserved.
7-38 Copyright © 2007, Oracle. All rights reserved.

Anda mungkin juga menyukai