Upload
richard-green
View
224
Download
0
Tags:
Embed Size (px)
Citation preview
7Copyright © 2005, Oracle. All rights reserved.
Creating Classes and Objects
7-2 Copyright © 2005, 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-4 Copyright © 2005, Oracle. All rights reserved.
Using Java Classes
Packages
Methods Objects
Objectreferences
Attributes
Contained in a class
7-5 Copyright © 2005, Oracle. All rights reserved.
title: “Gone with…”rating: “PG”
title: “Last Action…”rating: “PG-13”
Comparing Classes and Objects
• An object is an instance of a class.
• Objects have their own memory.
• Class definitions must be loaded to create instances.
public void displayDetails()
private String title;
private String rating;
public void setRating()
Movie
mov1 mov2
7-6 Copyright © 2005, Oracle. All rights reserved.
Creating Objects
• Objects are typically created by using the new operator:
• For example, to create two Movie objects:
Movie mov1 = new Movie("Gone ...");
Movie mov2 = new Movie("Last ...");
ClassName objectRef = new ClassName();
title: “Gone with…”rating: “PG”
title: “Last Action…”rating: “PG-13”
7-7 Copyright © 2005, Oracle. All rights reserved.
Using the 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, called a constructor
• Returns a reference to the new object
Movie mov1 = new Movie("Gone with…");
mov1(When instantiated)
title: “Gone with…”rating: “PG”
7-8 Copyright © 2005, Oracle. All rights reserved.
Comparing Primitives and Objects
Primitive variables hold a value.
int i;
int j = 3; Movie mov1 = new Movie();
Object variableshold references.
title: nullrating: null
mov1
Movie mov1;
mov10
3
i
j
null
7-9 Copyright © 2005, Oracle. All rights reserved.
Using the null Reference
• A special null value may 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-10 Copyright © 2005, 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
Movie mov2 = mov1;
mov2
title: “Gone with…”rating: “PG”
7-11 Copyright © 2005, Oracle. All rights reserved.
title: nullrating: null
title: nullrating: null
Declaring Instance Variables
Instance variables are declared within the class, but outside the methods or instance or static intializers.
public class Movie {
public String title;
public String rating;
public float getPrice(){
return price;
}
}
Movie mov1 = new Movie();
Movie mov2 = new Movie();
mov2
mov1
Create movies:
7-12 Copyright © 2005, Oracle. All rights reserved.
Accessing public Instance Variables
public instance variables can be accessed by usingthe 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-13 Copyright © 2005, 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-14 Copyright © 2005, 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-15 Copyright © 2005, Oracle. All rights reserved.
Specifying Method Arguments: Examples
• Specify the number and type of arguments in the method definition:
• If the method takes no arguments, then leave the parentheses empty:
public void displayDetails() {
System.out.println("Title is " + title);
System.out.println("Rating is " + rating);
}
public void setRating(String newRating) {
rating = newRating;
}
7-16 Copyright © 2005, 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:
• If the return type is void, then no return is needed.
• You can use a return without a value to terminate a method with a void return type.
public class Movie { private String rating; … public String getRating () { return rating }}
7-17 Copyright © 2005, 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();
if (r.equals("G")) … Use the dot operator:
7-18 Copyright © 2005, Oracle. All rights reserved.
Applying Encapsulation in Java
• Instance variables must be declared as private.
• Only instance methods can access private instance variables.
• private decouples the interface 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"))
var
aMethod
aMethod()
7-19 Copyright © 2005, Oracle. All rights reserved.
Passing Primitives into Methods
When a primitive or object reference value is passed into a method, a copy of the value is generated:
public void aMethod(int arg) {
if (arg < 0 || arg > 100)
arg = 0;
System.out.println("arg: " + arg);
}
int num = 150;
anObj.aMethod(num);
System.out.println("num: " + num);
arg150
num150
7-20 Copyright © 2005, Oracle. All rights reserved.
title: “Gone with…”rating: “PG”
Passing Object References into Methods
When an object reference is passed into a method, the object is not copied but the pointer to the object is copied:
public void aMethod(Movie ref2) {
ref2.setRating("R");
}
mov1
ref2
Movie mov1 =
new Movie("Gone…");
mov1.setRating("PG");
anObj.aMethod(mov1);
7-21 Copyright © 2005, Oracle. All rights reserved.
What Are 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
Movie class variable Movie objects
titlerating
titlerating
titlerating
minPrice
7-22 Copyright © 2005, 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 data type.
public class Movie {
private static double minPrice = 1.29;
private String title, rating;
private int length = 0;
7-23 Copyright © 2005, Oracle. All rights reserved.
What Are Class Methods?
Class methods are:
• Shared by all instances
• Useful for manipulating class variables
• Declared as static
A class method is called by using the name of the class or an object reference.
public static void increaseMinPrice(double inc) {
minPrice += inc;
}
Movie.increaseMinPrice(.50);
mov1.increaseMinPrice(.50);
7-24 Copyright © 2005, Oracle. All rights reserved.
Guided Practice: Class Methodsor 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 String; }}
Movie.setPrice(3.98f); Movie mov1 = new Movie(…);mov1.setPrice(3.98f);String a = Movie.getRating();String b = mov1.getRating();Legal or not?
7-25 Copyright © 2005, 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-26 Copyright © 2005, Oracle. All rights reserved.
Creating Classes Using the Class Editor
7-27 Copyright © 2005, Oracle. All rights reserved.
What Are Java Packages?
oe
Customer Order Util
OrderEntry OrderItem
7-28 Copyright © 2005, 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, then 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 contains the directory having
the root name of the package tree– That the class name must be qualified by its
package name
7-29 Copyright © 2005, 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
C:\>set CLASSPATH=E:\Curriculum\courses\java\les06CLASSPATH
7-30 Copyright © 2005, Oracle. All rights reserved.
Access Modifiers
private
protected
acmevideo acmetools
public public
7-32 Copyright © 2005, 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-33 Copyright © 2005, Oracle. All rights reserved.
Practice 7: Overview
This practice covers:
• Defining new classes
• Specifying the classes’ instance variables and instance methods
• Creating Customer objects in main()• Manipulating Customer objects by using public
instance methods