7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects

download 7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects

of 36

  • date post

    27-Mar-2015
  • Category

    Documents

  • view

    217
  • download

    0

Embed Size (px)

Transcript of 7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects

  • Slide 1

7 Copyright 2005, Oracle. All rights reserved. Creating Classes and Objects Slide 2 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 Slide 3 7-3 Copyright 2005, Oracle. All rights reserved. Notes page Slide 4 7-4 Copyright 2005, Oracle. All rights reserved. Using Java Classes Packages MethodsObjects Object references Attributes Contained in a class Slide 5 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 mov1mov2 Slide 6 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 Slide 7 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 Slide 8 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 variables hold references. title: null rating: null mov1 Movie mov1; mov1 0 3 i j null Slide 9 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 Slide 10 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 Slide 11 7-11 Copyright 2005, Oracle. All rights reserved. title: null rating: null title: null rating: 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 : Slide 12 7-12 Copyright 2005, 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"; Slide 13 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 }; Slide 14 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 Slide 15 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; } Slide 16 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 } Slide 17 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: Slide 18 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() Slide 19 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 100) arg = 0; System.out.println("arg: " + arg); } int num = 150; anObj.aMethod(num); System.out.println("num: " + num); arg 150 num 150 Slide 20 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); Slide 21 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 title rating title rating title rating min Price Slide 22 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; Slide 23 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); Slide 24 7-24 Copyright 2005, 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 String; } Movie.setPrice(3.98f); Movie mov1 = new Movie(); mov1.setPrice(3.98f); String a = Movie.getRating(); String b = mov1.getRating(); Legal or not? Slide 25 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); } Slide 26 7-26 Copyright 2005, Oracle. All rights reserved. Creating Classes Using the Class Editor Slide 27 7-27 Copyright 2005, Oracle. All rights reserved. What Are Java Packages? oe CustomerOrderUtil OrderEntryOrderItem Slide 28 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 Slide 29 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\les06 CLASSPATH Slide 30 7-30 Copyright 2005, Oracle. All rights reserved. Access Modifiers private protected acmevideoacmetools public Slide 31 7-31 Copyright 2005, Oracle. All rights reserved. Notes page Slide 32 7-32 Copyright 2005, Oracle. All rights reserved. Summary In this lesson, you sh