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

Slides:



Advertisements
Similar presentations
UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1.
Advertisements

Final and Abstract Classes
1 Packages: Putting Classes Together. 2 Introduction The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance)
Classes and Objects in Java
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 14 Inheritance. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Inheritance Basics Derived classes, with.
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
© 2008 Pearson Addison Wesley. All rights reserved Chapter Seven Costs.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 1 The Study of Body Function Image PowerPoint
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
1 Copyright © 2013 Elsevier Inc. All rights reserved. Appendix 01.
1 Copyright © 2013 Elsevier Inc. All rights reserved. Chapter 3 CPUs.
Properties Use, share, or modify this drill on mathematic properties. There is too much material for a single class, so you’ll have to select for your.
UNITED NATIONS Shipment Details Report – January 2006.
12 Copyright © 2005, Oracle. All rights reserved. Structuring Code Using Abstract Classes and Interfaces.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
8 Copyright © 2005, Oracle. All rights reserved. Object Life Cycle and Inner Classes.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
6 Copyright © 2005, Oracle. All rights reserved. Building Applications with Oracle JDeveloper 10g.
1 RA I Sub-Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Casablanca, Morocco, 20 – 22 December 2005 Status of observing programmes in RA I.
FACTORING ax2 + bx + c Think “unfoil” Work down, Show all steps.
4-1 Chapter 4 (a) Defining Classes. 4-2 The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects.
REVIEW: Arthropod ID. 1. Name the subphylum. 2. Name the subphylum. 3. Name the order.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
Chapter 17 Linked Lists.
Chapter 24 Lists, Stacks, and Queues
1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.
Semantic Analysis and Symbol Tables
2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
Understanding class definitions Looking inside classes 5.0.
21-Aug-14 Basic Object-Oriented Concepts. 2 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions,
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
Factor P 16 8(8-5ab) 4(d² + 4) 3rs(2r – s) 15cd(1 + 2cd) 8(4a² + 3b²)
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
© 2012 National Heart Foundation of Australia. Slide 2.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Understanding Generalist Practice, 5e, Kirst-Ashman/Hull
 2000 Prentice Hall, Inc. All rights reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction 14.2Redirecting Input/Output on UNIX and DOS Systems.
1 Variables and Data Types. 2 Variable Definition a location in memory, referenced by a name (identifier), where data of a given type can be stored, changed,
Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Analyzing Genes and Genomes
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
Pointers and Arrays Chapter 12
Intracellular Compartments and Transport
PSSA Preparation.
Essential Cell Biology
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Copyright © 2012 Pearson Education, Inc. Chapter 14: More About Classes.
Energy Generation in Mitochondria and Chlorplasts
Abstract Class, Packages and interface from Chapter 9
1 Abstract Class and Packages from Chapter 9 Lecture.
User Defined Functions Lesson 1 CS1313 Fall User Defined Functions 1 Outline 1.User Defined Functions 1 Outline 2.Standard Library Not Enough #1.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Presentation transcript:

7 Copyright © 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-3 Copyright © 2005, Oracle. All rights reserved. Notes page

7-4 Copyright © 2005, Oracle. All rights reserved. Using Java Classes Packages MethodsObjects Object references 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 mov1mov2

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 variables hold references. title: null rating: null mov1 Movie mov1; mov1 0 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: 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 :

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";

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 100) arg = 0; System.out.println("arg: " + arg); } int num = 150; anObj.aMethod(num); System.out.println("num: " + num); arg 150 num 150

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 title rating title rating title rating min Price

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 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?

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 CustomerOrderUtil OrderEntryOrderItem

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\les06 CLASSPATH

7-30 Copyright © 2005, Oracle. All rights reserved. Access Modifiers private protected acmevideoacmetools public

7-31 Copyright © 2005, Oracle. All rights reserved. Notes page

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

7-34 Copyright © 2005, Oracle. All rights reserved. Notes Page for Practice 7

7-35 Copyright © 2005, Oracle. All rights reserved. Practice 7: Notes

7-36 Copyright © 2005, Oracle. All rights reserved.