BCSE103E Module 3: Objects and Classes Dr. S Ranjithkumar M.E., Ph.D. Assistant Professor Senior Grade 1 School of Computer Science and Engineering, Vellore Institute of Technology, Vellore – 632014 Phone No: +91 9944401999 Mail ID: ranjithkumar.s@vit.ac.in Location: PRP Block – 315 AB21
2 OO Programming Concepts • Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.
3 OO Programming Concepts • The state of an object (also known as its properties or attributes) is represented by data fields with their current values. A circle object, for example, has a data field radius, which is the property that characterizes a circle. A rectangle object has the data fields width and height, which are the properties that characterize a rectangle • The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an object is to ask the object to perform an action. For example, you may define methods named getArea() and getPerimeter() for circle objects. A circle object may invoke getArea() to return its area and getPerim- eter() to return its perimeter.
4 OO Programming Concepts • Objects of the same type are defined using a common class. A class is a template, blueprint, or contract that defines what an object’s data fields and methods will be. An object is an instance of a class. You can create many instances of a class. Creating an instance is referred to as instantiation. • The terms object and instance are often interchangeable. The relationship between classes and objects is analogous to that between an apple-pie recipe and apple pies: You can make as many apple pies as you want from a single recipe.
5 Objects An object has both a state and behavior. The state defines the object, and the behavior defines what the object does. Class Name: Circle Data Fields: radius is _______ Methods: getArea Circle Object 1 Data Fields: radius is 10 Circle Object 2 Data Fields: radius is 25 Circle Object 3 Data Fields: radius is 125 A class template Three objects of the Circle class
6 Classes Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.
7 Classes class Circle { /** The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * 3.14159; } } Data field Method Constructors
8 Classes • The Circle class is different from all of the other classes you have seen thus far. It does not have a main method and therefore cannot be run; it is merely a definition for circle objects. The class that contains the main method will be referred to in this book, for convenience, as the main class. • The illustration of class templates and objects in can be standardized using Unified Modeling Language (UML) notation. This notation is called a UML class diagram, or simply a class diagram.
9 Unified Modeling Language (UML) Class Diagram In the class diagram, the data field is denoted as dataFieldName: dataFieldType The constructor is denoted as: ClassName(parameterName: parameterType) The method is denoted as methodName(parameterName: parameterType): returnType
10 Example: SimpleCircle class
11 Example: SimpleCircle class
12 Example: SimpleCircle class • The program contains two classes. The first of these, TestSimpleCircle, is the main class. Its sole purpose is to test the second class, SimpleCircle. Such a program that uses the class is often referred to as a client of the class. When you run the program, the Java runtime system invokes the main method in the main class. • You can put the two classes into one file, but only one class in the file can be a public class. Furthermore, the public class must have the same name as the file name. Therefore, the file name is TestSimpleCircle.java, since TestSimpleCircle is public. • Each class in the source code is compiled into a .class file. When you compile TestSimpleCircle.java, two class files TestSimpleCircle.class and SimpleCircle.class are generated,
Combine Two Classes into One 13
Combine Two Classes into One 14
15 Example: Defining Classes and Creating Objects TV channel: int volumeLevel: int on: boolean +TV() +turnOn(): void +turnOff(): void +setChannel(newChannel: int): void +setVolume(newVolumeLevel: int): void +channelUp(): void +channelDown(): void +volumeUp(): void +volumeDown(): void The current channel (1 to 120) of this TV. The current volume level (1 to 7) of this TV. Indicates whether this TV is on/off. Constructs a default TV object. Turns on this TV. Turns off this TV. Sets a new channel for this TV. Sets a new volume level for this TV. Increases the channel number by 1. Decreases the channel number by 1. Increases the volume level by 1. Decreases the volume level by 1. The + sign indicates a public modifier. The constructor and methods in the TV class are defined public so they can be accessed from other classes.
16 Example: Defining Classes and Creating Objects
17 Example: Defining Classes and Creating Objects
18 Constructors Circle() { } Circle(double newRadius) { radius = newRadius; } Constructors are a special kind of methods that are invoked to construct objects.
19 Constructors, cont. A constructor with no parameters is referred to as a no-arg constructor. · Constructors must have the same name as the class itself. · Constructors do not have a return type—not even void. · Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
20 Creating Objects Using Constructors new ClassName(); Example: new Circle(); new Circle(5.0);
21 Default Constructor A class may be defined without constructors. In this case, a no-arg constructor with an empty body is implicitly defined in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class.
22 Declaring Object Reference Variables Objects are accessed via the object’s reference variables, which contain references to the objects. To reference an object, assign the object to a reference variable. A class is a reference type, which means that a variable of the class type can reference an instance of the class. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle;
23 Declaring/Creating Objects in a Single Step ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); Create an object Assign object reference
24 Accessing Object’s Members  Referencing the object’s data is done using the dot operator or object member access operator: objectRefVar.data e.g., myCircle.radius  Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()
25 Trace Code Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; Declare myCircle no value myCircle
26 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 no value myCircle Create a circle
27 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle Assign object reference to myCircle
28 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle no value yourCircle Declare yourCircle
29 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle no value yourCircle : Circle radius: 1.0 Create a new Circle object
30 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle reference value yourCircle : Circle radius: 1.0 Assign object reference to yourCircle
31 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle reference value yourCircle : Circle radius: 100.0 Change radius in yourCircle
32 Caution The data field radius is referred to as an instance variable, because it is dependent on a specific instance. For the same reason, the method getArea is referred to as an instance method, because you can invoke it only on a specific instance. The object on which an instance method is invoked is called a calling object.
33 Caution Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using SimpleCircle.getArea()? The answer is 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()).
34 Reference Data Fields The data fields can be of reference types. 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' }
35 The null Value If a data field of a reference type does not reference any object, the data field holds a special literal value, null.
36 Default Value for a Data Field The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and 'u0000' for a char type. However, Java assigns no default value to a local variable inside a method. 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); } }
37 Example 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); } } Compile error: variable not initialized Java assigns no default value to a local variable inside a method.
38 Differences between Variables of Primitive Data Types and Object Types • Every variable represents a memory location that holds a value. When you declare a variable, you are telling the compiler what type of value the variable can hold. For a variable of a primitive type, the value is of the primitive type. For a variable of a reference type, the value is a reference to where an object is located.
39 Copying Variables of Primitive Data Types and Object Types
40 Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.
41 Garbage Collection, cont TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable.
42 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.
43 The Date Class Example
44 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. java.util.Random +Random() +Random(seed: long) +nextInt(): int +nextInt(n: int): int +nextLong(): long +nextDouble(): double +nextFloat(): float +nextBoolean(): boolean Constructs a Random object with the current time as its seed. Constructs a Random object with a specified seed. Returns a random int value. Returns a random int value between 0 and n (exclusive). Returns a random long value. Returns a random double value between 0.0 and 1.0 (exclusive). Returns a random float value between 0.0F and 1.0F (exclusive). Returns a random boolean value.
45 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
46 The Point2D Class Java API has a conveninent Point2D class in the javafx.geometry package for representing a point in a two- dimensional plane.
47 The Point2D Class
48 Instance Variables, and Methods • Instance variables belong to a specific instance. • Instance methods are invoked by any instance of the class.
49 Static Variables, Constants, and Methods • Static variables are shared by all the instances of the class. • Static methods are not tied to a specific object. Because of this, a static method cannot access instance members of the class • Static constants are final variables shared by all the instances of the class. • A non-static (or instance) variable is tied to a specific instance
50 Static Variables, Constants, and Methods • Static variables store values for the variables in a common memory location. Because of this common location, if one object changes the value of a static variable, all objects of the same class are affected. • Java supports static methods as well as static variables. Static methods can be called without creating an instance of the class.
51 Static Variables, Constants, and Methods, cont. • To declare static variables, constants, and methods, use the static modifier. For example, the constant PI in the Math class is defined as final static double PI=3.14159265358979323846 • Let’s modify the Circle class by adding a static variable numberOfObjects to count the number of circle objects created. When the first object of this class is created, numberOfObjects is 1. When the second object is created, numberOfObjects becomes 2. The UML of the new circle class is shown below
52 Static Variables, Constants, and Methods, cont.
53 CircleWithStaticMembers Class
54 TestCircleWithStaticMembers.java Static variables and methods can be accessed without creating objects. Line 6 displays the number of objects, which is 0, since no objects have been created.
55 Static and Instance Methods An instance method can invoke an instance or static method and access an instance or static data field. A static method can invoke a static method and access a static data field. However, a static method cannot invoke an instance method or access an instance data field, since static methods and static data fields don’t belong to a particular object.
56 Examples
57 Examples
58 Visibility Modifiers and Accessor/Mutator Methods You can use the public visibility modifier for classes, methods, and data fields to denote that they can be accessed from any other classes. If no visibility modifier is used, then by default the classes, methods, and data fields are accessible by any class in the same package. This is known as package-private or package-access. Packages can be used to organize classes. To do so, you need to add the following line as the first statement in the program: package packageName; If a class is defined without the package statement, it is said to be placed in the default package.
59 Visibility Modifiers and Accessor/Mutator Methods By default, the class, variable, or method can be accessed 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. Public getter (Accessor) and setter (Mutator) methods are used to read and modify private properties.
60 • The private modifier restricts access to within a class, • The default modifier restricts access to within a package, • The public modifier enables unrestricted access. Examples
61 • The default modifier on a class restricts access to within a package • The public modifier enables unrestricted access. Visibility Modifier of Classes
62 NOTE • An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).
63 NOTE • The private modifier applies only to the members of a class. The public modifier can apply to a class or members of a class. Using the modifiers public and private on local variables would cause a compile error. • In most cases, the constructor should be public. However, if you want to prohibit the user from creating an instance of a class, use a private constructor. For example, there is no reason to create an instance from the Math class, because all of its data fields and methods are static. To prevent the user from creating objects from the Math class, the constructor in java.lang.Math is defined as private.
64 Data Field Encapsulation Making data fields private protect data. Making data fields private helps to make code easy to maintain since the client programs cannot modify them. To prevent direct modifications of data fields, declaring the data fields private is known as data field encapsulation. To make a private data field accessible, provide a getter method to return its value. To enable a private data field to be updated, provide a setter method to set a new value. A getter method is also referred to as an accessor and a setter to a mutator.
65 Example of Data Field Encapsulation
66 Example of Data Field Encapsulation
67 Example of Data Field Encapsulation
68 Example of Data Field Encapsulation
69 Passing Objects to Methods  Passing by value for primitive type value (the value is passed to the parameter)  Passing by value for reference type value (the value is the reference to the object)
70 Passing Objects to Methods
71 Passing a primitive type value and a reference value
72 Passing a primitive type value and a reference value When passing an argument of a reference type, the reference of the object is passed. In this case, c contains a reference for the object that is also referenced via myCircle. Therefore, changing the properties of the object through c inside the printAreas method has the same effect as doing so outside the method through the variable myCircle. Pass-by-value on references can be best described semantically as pass-by- sharing; that is, the object referenced in the method is the same as the object being passed.
73 Passing Objects to Methods
74 Array of Objects Circle[] circleArray = new Circle[10]; An array of objects is actually an array of reference variables. So invoking circleArray[1].getArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.
75 Array of Objects Circle[] circleArray = new Circle[10];
76 Array of Objects To initialize circleArray, you can use a for loop for (int i = 0; i < circleArray.length; i++) { circleArray[i] = new Circle(); } An array of objects is actually an array of reference variables. When an array of objects is created using the new operator, each element in the array is a reference variable with a default value of null.
77 Summarizing the areas of the circles
78 Summarizing the areas of the circles
79 Summarizing the areas of the circles
80 Immutable Objects • Normally, you create an object and allow its contents to be changed later. However, occasionally it is desirable to create an object whose contents cannot be changed once the object has been created. We call such an object as immutable object and its class as immutable class. • If a class is immutable, then all its data fields must be private and it cannot contain public setter methods for any data fields. A class with all private data fields and no mutators is not necessarily immutable.
81 Example
82 Example
83 Scope of Variables  The scope of instance and static variables is the entire class. They can be declared anywhere inside a class.  The scope of a local variable (i.e. a variable defined in a method) starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used.
84 Scope of Variables
85 Scope of Variables • If a local variable has the same name as a class’s variable, the local variable takes precedence and the class’s variable with the same name is hidden.
86 The this Keyword  The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields.  Another common use of the this keyword to enable a constructor to invoke another constructor of the same class.
87 The this Keyword
88 Reference the Hidden Data Fields The this keyword can be used to reference a class’s hidden data fields. For example, a data-field name is often used as the parameter name in a setter method for the data field. In this case, the data field is hidden in the setter method. You need to reference the hidden data-field name in the method in order to set a new value to it. A hidden static variable can be accessed using the keyword this.
89 Reference the Hidden Data Fields The this keyword gives us a way to reference the object that invokes an instance method. To invoke f1.setI(10), this.i = i is executed, which assigns the value of parameter i to the data field i of this calling object f1. The keyword this refers to the object that invokes the instance method setI, as shown below:
90 Calling Overloaded Constructor The this keyword can be used to invoke another constructor of the same class. For example, you can rewrite the Circle class as follows:

Module 3 Class and Object.ppt

  • 1.
    BCSE103E Module 3: Objectsand Classes Dr. S Ranjithkumar M.E., Ph.D. Assistant Professor Senior Grade 1 School of Computer Science and Engineering, Vellore Institute of Technology, Vellore – 632014 Phone No: +91 9944401999 Mail ID: ranjithkumar.s@vit.ac.in Location: PRP Block – 315 AB21
  • 2.
    2 OO Programming Concepts •Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.
  • 3.
    3 OO Programming Concepts •The state of an object (also known as its properties or attributes) is represented by data fields with their current values. A circle object, for example, has a data field radius, which is the property that characterizes a circle. A rectangle object has the data fields width and height, which are the properties that characterize a rectangle • The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an object is to ask the object to perform an action. For example, you may define methods named getArea() and getPerimeter() for circle objects. A circle object may invoke getArea() to return its area and getPerim- eter() to return its perimeter.
  • 4.
    4 OO Programming Concepts •Objects of the same type are defined using a common class. A class is a template, blueprint, or contract that defines what an object’s data fields and methods will be. An object is an instance of a class. You can create many instances of a class. Creating an instance is referred to as instantiation. • The terms object and instance are often interchangeable. The relationship between classes and objects is analogous to that between an apple-pie recipe and apple pies: You can make as many apple pies as you want from a single recipe.
  • 5.
    5 Objects An object hasboth a state and behavior. The state defines the object, and the behavior defines what the object does. Class Name: Circle Data Fields: radius is _______ Methods: getArea Circle Object 1 Data Fields: radius is 10 Circle Object 2 Data Fields: radius is 25 Circle Object 3 Data Fields: radius is 125 A class template Three objects of the Circle class
  • 6.
    6 Classes Classes are constructsthat define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.
  • 7.
    7 Classes class Circle { /**The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * 3.14159; } } Data field Method Constructors
  • 8.
    8 Classes • The Circleclass is different from all of the other classes you have seen thus far. It does not have a main method and therefore cannot be run; it is merely a definition for circle objects. The class that contains the main method will be referred to in this book, for convenience, as the main class. • The illustration of class templates and objects in can be standardized using Unified Modeling Language (UML) notation. This notation is called a UML class diagram, or simply a class diagram.
  • 9.
    9 Unified Modeling Language(UML) Class Diagram In the class diagram, the data field is denoted as dataFieldName: dataFieldType The constructor is denoted as: ClassName(parameterName: parameterType) The method is denoted as methodName(parameterName: parameterType): returnType
  • 10.
  • 11.
  • 12.
    12 Example: SimpleCircle class •The program contains two classes. The first of these, TestSimpleCircle, is the main class. Its sole purpose is to test the second class, SimpleCircle. Such a program that uses the class is often referred to as a client of the class. When you run the program, the Java runtime system invokes the main method in the main class. • You can put the two classes into one file, but only one class in the file can be a public class. Furthermore, the public class must have the same name as the file name. Therefore, the file name is TestSimpleCircle.java, since TestSimpleCircle is public. • Each class in the source code is compiled into a .class file. When you compile TestSimpleCircle.java, two class files TestSimpleCircle.class and SimpleCircle.class are generated,
  • 13.
  • 14.
  • 15.
    15 Example: Defining Classesand Creating Objects TV channel: int volumeLevel: int on: boolean +TV() +turnOn(): void +turnOff(): void +setChannel(newChannel: int): void +setVolume(newVolumeLevel: int): void +channelUp(): void +channelDown(): void +volumeUp(): void +volumeDown(): void The current channel (1 to 120) of this TV. The current volume level (1 to 7) of this TV. Indicates whether this TV is on/off. Constructs a default TV object. Turns on this TV. Turns off this TV. Sets a new channel for this TV. Sets a new volume level for this TV. Increases the channel number by 1. Decreases the channel number by 1. Increases the volume level by 1. Decreases the volume level by 1. The + sign indicates a public modifier. The constructor and methods in the TV class are defined public so they can be accessed from other classes.
  • 16.
    16 Example: Defining Classesand Creating Objects
  • 17.
    17 Example: Defining Classesand Creating Objects
  • 18.
    18 Constructors Circle() { } Circle(double newRadius){ radius = newRadius; } Constructors are a special kind of methods that are invoked to construct objects.
  • 19.
    19 Constructors, cont. A constructorwith no parameters is referred to as a no-arg constructor. · Constructors must have the same name as the class itself. · Constructors do not have a return type—not even void. · Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
  • 20.
    20 Creating Objects Using Constructors newClassName(); Example: new Circle(); new Circle(5.0);
  • 21.
    21 Default Constructor A classmay be defined without constructors. In this case, a no-arg constructor with an empty body is implicitly defined in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class.
  • 22.
    22 Declaring Object ReferenceVariables Objects are accessed via the object’s reference variables, which contain references to the objects. To reference an object, assign the object to a reference variable. A class is a reference type, which means that a variable of the class type can reference an instance of the class. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle;
  • 23.
    23 Declaring/Creating Objects in aSingle Step ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); Create an object Assign object reference
  • 24.
    24 Accessing Object’s Members Referencing the object’s data is done using the dot operator or object member access operator: objectRefVar.data e.g., myCircle.radius  Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()
  • 25.
    25 Trace Code Circle myCircle= new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; Declare myCircle no value myCircle
  • 26.
    26 Trace Code, cont. CirclemyCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 no value myCircle Create a circle
  • 27.
    27 Trace Code, cont. CirclemyCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle Assign object reference to myCircle
  • 28.
    28 Trace Code, cont. CirclemyCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle no value yourCircle Declare yourCircle
  • 29.
    29 Trace Code, cont. CirclemyCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle no value yourCircle : Circle radius: 1.0 Create a new Circle object
  • 30.
    30 Trace Code, cont. CirclemyCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle reference value yourCircle : Circle radius: 1.0 Assign object reference to yourCircle
  • 31.
    31 Trace Code, cont. CirclemyCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; : Circle radius: 5.0 reference value myCircle reference value yourCircle : Circle radius: 100.0 Change radius in yourCircle
  • 32.
    32 Caution The data fieldradius is referred to as an instance variable, because it is dependent on a specific instance. For the same reason, the method getArea is referred to as an instance method, because you can invoke it only on a specific instance. The object on which an instance method is invoked is called a calling object.
  • 33.
    33 Caution Recall that youuse Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using SimpleCircle.getArea()? The answer is 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()).
  • 34.
    34 Reference Data Fields Thedata fields can be of reference types. 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' }
  • 35.
    35 The null Value Ifa data field of a reference type does not reference any object, the data field holds a special literal value, null.
  • 36.
    36 Default Value fora Data Field The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and 'u0000' for a char type. However, Java assigns no default value to a local variable inside a method. 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); } }
  • 37.
    37 Example 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); } } Compile error: variable not initialized Java assigns no default value to a local variable inside a method.
  • 38.
    38 Differences between Variablesof Primitive Data Types and Object Types • Every variable represents a memory location that holds a value. When you declare a variable, you are telling the compiler what type of value the variable can hold. For a variable of a primitive type, the value is of the primitive type. For a variable of a reference type, the value is a reference to where an object is located.
  • 39.
    39 Copying Variables ofPrimitive Data Types and Object Types
  • 40.
    40 Garbage Collection As shownin the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.
  • 41.
    41 Garbage Collection, cont TIP:If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable.
  • 42.
    42 The Date Class Javaprovides 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.
  • 43.
  • 44.
    44 The Random Class Youhave 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. java.util.Random +Random() +Random(seed: long) +nextInt(): int +nextInt(n: int): int +nextLong(): long +nextDouble(): double +nextFloat(): float +nextBoolean(): boolean Constructs a Random object with the current time as its seed. Constructs a Random object with a specified seed. Returns a random int value. Returns a random int value between 0 and n (exclusive). Returns a random long value. Returns a random double value between 0.0 and 1.0 (exclusive). Returns a random float value between 0.0F and 1.0F (exclusive). Returns a random boolean value.
  • 45.
    45 The Random ClassExample 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
  • 46.
    46 The Point2D Class JavaAPI has a conveninent Point2D class in the javafx.geometry package for representing a point in a two- dimensional plane.
  • 47.
  • 48.
    48 Instance Variables, andMethods • Instance variables belong to a specific instance. • Instance methods are invoked by any instance of the class.
  • 49.
    49 Static Variables, Constants, andMethods • Static variables are shared by all the instances of the class. • Static methods are not tied to a specific object. Because of this, a static method cannot access instance members of the class • Static constants are final variables shared by all the instances of the class. • A non-static (or instance) variable is tied to a specific instance
  • 50.
    50 Static Variables, Constants, andMethods • Static variables store values for the variables in a common memory location. Because of this common location, if one object changes the value of a static variable, all objects of the same class are affected. • Java supports static methods as well as static variables. Static methods can be called without creating an instance of the class.
  • 51.
    51 Static Variables, Constants, andMethods, cont. • To declare static variables, constants, and methods, use the static modifier. For example, the constant PI in the Math class is defined as final static double PI=3.14159265358979323846 • Let’s modify the Circle class by adding a static variable numberOfObjects to count the number of circle objects created. When the first object of this class is created, numberOfObjects is 1. When the second object is created, numberOfObjects becomes 2. The UML of the new circle class is shown below
  • 52.
  • 53.
  • 54.
    54 TestCircleWithStaticMembers.java Static variables and methodscan be accessed without creating objects. Line 6 displays the number of objects, which is 0, since no objects have been created.
  • 55.
    55 Static and InstanceMethods An instance method can invoke an instance or static method and access an instance or static data field. A static method can invoke a static method and access a static data field. However, a static method cannot invoke an instance method or access an instance data field, since static methods and static data fields don’t belong to a particular object.
  • 56.
  • 57.
  • 58.
    58 Visibility Modifiers andAccessor/Mutator Methods You can use the public visibility modifier for classes, methods, and data fields to denote that they can be accessed from any other classes. If no visibility modifier is used, then by default the classes, methods, and data fields are accessible by any class in the same package. This is known as package-private or package-access. Packages can be used to organize classes. To do so, you need to add the following line as the first statement in the program: package packageName; If a class is defined without the package statement, it is said to be placed in the default package.
  • 59.
    59 Visibility Modifiers andAccessor/Mutator Methods By default, the class, variable, or method can be accessed 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. Public getter (Accessor) and setter (Mutator) methods are used to read and modify private properties.
  • 60.
    60 • The privatemodifier restricts access to within a class, • The default modifier restricts access to within a package, • The public modifier enables unrestricted access. Examples
  • 61.
    61 • The defaultmodifier on a class restricts access to within a package • The public modifier enables unrestricted access. Visibility Modifier of Classes
  • 62.
    62 NOTE • An objectcannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).
  • 63.
    63 NOTE • The privatemodifier applies only to the members of a class. The public modifier can apply to a class or members of a class. Using the modifiers public and private on local variables would cause a compile error. • In most cases, the constructor should be public. However, if you want to prohibit the user from creating an instance of a class, use a private constructor. For example, there is no reason to create an instance from the Math class, because all of its data fields and methods are static. To prevent the user from creating objects from the Math class, the constructor in java.lang.Math is defined as private.
  • 64.
    64 Data Field Encapsulation Makingdata fields private protect data. Making data fields private helps to make code easy to maintain since the client programs cannot modify them. To prevent direct modifications of data fields, declaring the data fields private is known as data field encapsulation. To make a private data field accessible, provide a getter method to return its value. To enable a private data field to be updated, provide a setter method to set a new value. A getter method is also referred to as an accessor and a setter to a mutator.
  • 65.
  • 66.
  • 67.
    67 Example of DataField Encapsulation
  • 68.
    68 Example of DataField Encapsulation
  • 69.
    69 Passing Objects toMethods  Passing by value for primitive type value (the value is passed to the parameter)  Passing by value for reference type value (the value is the reference to the object)
  • 70.
  • 71.
    71 Passing a primitivetype value and a reference value
  • 72.
    72 Passing a primitivetype value and a reference value When passing an argument of a reference type, the reference of the object is passed. In this case, c contains a reference for the object that is also referenced via myCircle. Therefore, changing the properties of the object through c inside the printAreas method has the same effect as doing so outside the method through the variable myCircle. Pass-by-value on references can be best described semantically as pass-by- sharing; that is, the object referenced in the method is the same as the object being passed.
  • 73.
  • 74.
    74 Array of Objects Circle[]circleArray = new Circle[10]; An array of objects is actually an array of reference variables. So invoking circleArray[1].getArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.
  • 75.
    75 Array of Objects Circle[]circleArray = new Circle[10];
  • 76.
    76 Array of Objects Toinitialize circleArray, you can use a for loop for (int i = 0; i < circleArray.length; i++) { circleArray[i] = new Circle(); } An array of objects is actually an array of reference variables. When an array of objects is created using the new operator, each element in the array is a reference variable with a default value of null.
  • 77.
  • 78.
  • 79.
  • 80.
    80 Immutable Objects • Normally,you create an object and allow its contents to be changed later. However, occasionally it is desirable to create an object whose contents cannot be changed once the object has been created. We call such an object as immutable object and its class as immutable class. • If a class is immutable, then all its data fields must be private and it cannot contain public setter methods for any data fields. A class with all private data fields and no mutators is not necessarily immutable.
  • 81.
  • 82.
  • 83.
    83 Scope of Variables The scope of instance and static variables is the entire class. They can be declared anywhere inside a class.  The scope of a local variable (i.e. a variable defined in a method) starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used.
  • 84.
  • 85.
    85 Scope of Variables •If a local variable has the same name as a class’s variable, the local variable takes precedence and the class’s variable with the same name is hidden.
  • 86.
    86 The this Keyword The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields.  Another common use of the this keyword to enable a constructor to invoke another constructor of the same class.
  • 87.
  • 88.
    88 Reference the HiddenData Fields The this keyword can be used to reference a class’s hidden data fields. For example, a data-field name is often used as the parameter name in a setter method for the data field. In this case, the data field is hidden in the setter method. You need to reference the hidden data-field name in the method in order to set a new value to it. A hidden static variable can be accessed using the keyword this.
  • 89.
    89 Reference the HiddenData Fields The this keyword gives us a way to reference the object that invokes an instance method. To invoke f1.setI(10), this.i = i is executed, which assigns the value of parameter i to the data field i of this calling object f1. The keyword this refers to the object that invokes the instance method setI, as shown below:
  • 90.
    90 Calling Overloaded Constructor Thethis keyword can be used to invoke another constructor of the same class. For example, you can rewrite the Circle class as follows: