1 / 65

Chapter 7 Objects and Classes

Chapter 7 Objects and Classes. OO Programming Concepts. An Object corresponds to entity in the real world. Each object has a unique identity state – properties that can change in value behaviors – what can the object do?. OO Programming Concepts.

ghopkins
Télécharger la présentation

Chapter 7 Objects and Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7 Objects and Classes

  2. OO Programming Concepts • An Object corresponds to entity in the real world. • Each object has a unique • identity • state – properties that can change in value • behaviors – what can the object do?

  3. OO Programming Concepts An object encapsulates (wraps together) • attributes (data) • behaviors (methods) Goal: Information Hiding

  4. OOP Interface - what the object can do, proper usage vs. Implementation – how the object works

  5. Objects An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

  6. Classes • Classes define objects of the same type. • Class consists of • Variables – data • Methods – behavior

  7. Constructors • Methods that are used to instantiate a class • Have the same name as the class • Do not return a value Note: a method can have the same name as the class and have a return type - It’s not a constructor!

  8. Classes

  9. UML Class Diagram

  10. Constructors Constructors are a special kind of methods that are invoked to construct objects. Circle() { } Circle(double newRadius) { radius = newRadius; }

  11. Constructors · have the same name as class ·       have no return type—not even void ·       invoked using new operator at object creation Constructors initialize objects. Constructors can be overloaded. Constructors, cont.

  12. Creating Objects Using Constructors new ClassName(); Example: new Circle(); new Circle(5.0);

  13. Default Constructor A class may be declared without constructors. A constructor with no parameters is referred to as a no-arg constructor. No-arg constructor with empty body is implicitly declared. This default constructor is provided automatically only if no constructors are explicitly declared.

  14. Declaring Object Reference Variables To reference an object, assign the object to a reference variable. Syntax: ClassName objectRefVar; Example: Circle myCircle;

  15. Declaring/Creating Objectsin a Single Step ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); Create an object Assign object reference

  16. Dot Operator • Referencing the object’s data: objectRefVar.data e.g., myCircle.radius • Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()

  17. A Simple Circle Class • Objective: Demonstrate creating objects, accessing data, and using methods. TestCircle1 Run

  18. animation Declare myCircle Trace Code Circle myCircle = new Circle(5.0); SCircle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value

  19. animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle no value Create a circle

  20. animation Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; myCircle reference value Assign object reference to myCircle

  21. animation Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; Trace Code, cont. myCircle reference value yourCircle no value Declare yourCircle

  22. animation Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; Trace Code, cont. myCircle reference value yourCircle no value Create a new Circle object

  23. animation Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; Trace Code, cont. myCircle reference value yourCircle reference value Assign object reference to yourCircle

  24. animation Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; Trace Code, cont. myCircle reference value yourCircle reference value Change radius in yourCircle

  25. Caution We use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using Circle.getArea()? NO! All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).

  26. Reference Data Fields The data fields can be of primitive types OR reference types - Composition of objects For example, the following Student class contains a data field name of the String type. public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value '\u0000' }

  27. The null Value If data field of reference type does not reference any object, it holds a special literal value, null.

  28. Default Values Data fields of an object have default values. Variables defined in a method do not assume default values.

  29. Default Value for a Data Field Default value of data field: • null for reference type • 0 for a numeric type • false for a boolean type • '\u0000' for char type. public class Test { public static void main(String[] args) { Student student = new Student(); System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); } }

  30. Example Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); } } Compilation error: variables not initialized

  31. Differences between Variables of Primitive Data Types and Object Types

  32. Copying Variables of Primitive Data Types and Object Types

  33. Garbage Collection An assignment statement such as c1=c2 results in 2 objects pointing to the same object. The object previously referenced by c1 is no longer referenced so it is garbage. Garbage is automatically collected by JVM.

  34. Garbage Collection, cont TIP: If an object is no longer needed, explicitly assign null to a variable that references the object. The JVM automatically collects the space of an object not referenced by any variable.

  35. The Date Class Java provides a system-independent encapsulation of date and time in the java.util.Date class. You can use the Date class to create an instance for the current date and time and use its toString method to return the date and time as a string.

  36. The Date Class Example For example, the following code java.util.Date date = new java.util.Date(); System.out.println(date.toString()); displays a string likeSun Mar 09 13:50:19 EST 2003.

  37. The Random Class You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class.

  38. The Random Class Example If two Random objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3. Random random1 = new Random(3); System.out.print("From random1: "); for (int i = 0; i < 10; i++) System.out.print(random1.nextInt(1000) + " "); Random random2 = new Random(3); System.out.print("\nFrom random2: "); for (int i = 0; i < 10; i++) System.out.print(random2.nextInt(1000) + " "); From random1: 734 660 210 581 128 202 549 564 459 961 From random2: 734 660 210 581 128 202 549 564 459 961

  39. Instance Variables, and Methods Instance variables belong to a specific instance.Instance methods are invoked by an instance of the class. The dot operator

  40. Static Variables, Constants, and Methods Static variables are shared by all the instances of the class, class-wide information.Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.

  41. Static Variables, Constants, and Methods, cont. To declare static variables, constants, and methods, use the static modifier. The members of the math class are defined as static. That’s why we never create an object of type Math, yet we can use its methods.

  42. Static Variables, Constants, and Methods, cont.

  43. Example ofUsing Instance and Class Variables and Method Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberOfObjects to track the number of Circle objects created. Circle2 TestCircle2 Run

  44. Final instance variables • A final variable is not modifiable. • A constant can be initialized • In its declaration • By constructors • Syntax error: not initializing constant variable at declaration or in every constructor.

  45. Access to a Class Access level modifiers determine whether other classes can use a particular field OR or invoke a particular method.

  46. Access Control • Top Level • Public • Package-private (no explicit modifier) • Member Level • Public • Private • Protected – in any subclass or within package • Package-private (no explicit modifier)

  47. Access Levels

  48. Visibility Modifiers and Accessor/Mutator Methods By default, the class, variable, or method can beaccessed by any class in the same package. • public The class, data, or method is visible to any class in any package. • private The data or methods can be accessed only by the declaring class.

  49. Top Level Access Modifiers Member Level Access Modifiers

More Related