0% found this document useful (0 votes)
6 views

Unit 9: Objects and Classes

Uploaded by

Dũng Phạm
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 9: Objects and Classes

Uploaded by

Dũng Phạm
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT 9: OBJECTS AND CLASSES

1. Introduction
- Object-oriented programming is essentially a technology for developing reusable
software.
- To solve real-world problems using software, we’d like to define the real world’s
structure with attributes that exhibit the characteristics of the structure
- However, basic features like selections, loops, methods and arrays are not
sufficient for developing graphical user interfaces and large-scale software
systems.
=> The idea of Class and Objects comes into the picture in object-oriented
programming.

2. Object
- An object represents an entity in the real world that can be distinctly identified.
(ex: a student, a desk,…)
- An object consists of three unique things:
+ Identity: It gives a unique name to an object and enables one object to interact
with other objects.
+ State:
 Known as its properties and attributes
 Is represented by data fields with their current values
+ Behavior:
 Known as its actions
 Defined by methods (to invoke a method on an object is to ask the object to
perform an action)
- Example: “Dog” is a real-life object, which has some characteristics like color,
Breed, Bark, Sleep and Eat.
- Objects of the same type are defined using a common class.

3. Class
- A class is a template, blueprint, or contract that defines what an object’s data
fields and methods will be
- A class description consists of two things:
+ Attributes or member variables
+ Implementations of behavior or member functions.

- The differences between Class and Object:


CLASS OBJECT
Class is used as a template for An object is an instance of a class
declaring and creating the objects
When a class is created, no memory is Objects are allocated memory space
allocated whenever they are created
The class has to be declared first and An object is created many times as per
only once requirement
A class can’t be manipulated as they Objects can be manipulated
are not available in the memory
A class is a logical entity An object is a physical entity
It is declared with the “class” keyword It is created with the “new” keywords
Class does not contain any values Each objects has its own value, which
which can be associated with the field are associated with it
A class is used to bind data as well as Objects are like a variable of the class
methods together as a single unit
Example: bike Example: Ducati, Suzuki, Kawasaki

4. Example: Defining Classes and Creating Objects

public class Dog {


// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed, int age,
String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName() { return name; }

// method 2
public String getBreed() { return breed; }

// method 3
public int getAge() { return age; }

// method 4
public String getColor() { return color; }

@Override public String toString()


{
return ("Hi my name is " + this.getName()
+ ".\nMy breed,age and color are "
+ this.getBreed() + "," + this.getAge()
+ "," + this.getColor());
}

public static void main(String[] args)


{
Dog tuffy
= new Dog("tuffy", "papillon", 5, "white");
System.out.println(tuffy.toString());
}
}

Output:
Hi my name is tuffy.
My breed,age and color are papillon,5,white
5. Constructing objects using constructors
- A constructor is invoked to create an object using the new operator
- Constructors are a special kind of method. They have three peculiarities (nét
riêng biệt):
+ A constructor 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
- Constructors can be overloaded (multiple constructors can have the same name
but different signatures)
- Example:
// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main


(This will call the constructor)

System.out.println(myObj.x); // Print the value of x

}
// Outputs 5

6. Accessing objects via Reference Variables


6.1 Reference Variables and Reference Types
- Objects are accessed via the object’s reference variables, which contain
references to the objects. Such variables are declared using the following syntax:
ClassName objectRefVar;

- A class is a reference type, which means that a variable of the class type can
reference an instance of the class
Circle myCircle;
The variable myCircle can reference a Circle object. The next statement creates an
object and assigns its reference to myCircle:
myCircle = new Circle();
6.2 Accessing and Object’s Data and Methods
- After an object is created, its data can be accessed and its methods can be invoked
using the dot operator (.), also known as the object member access operator:
+ objectRefVar.dataField references a data field in the object.
+ objectRefVar.method(arguments) invokes a method on the object
- Example: myCircle.radius references the radius in myCircle and myCircle.getArea() invokes the
getArea method on myCircle.

6.3 Reference Data Fields and the null value


- If a data field of a reference type does not reference any object, the data field
holds a special Java value, null.
- null is a literal just like true and false. While true and false are Boolean literals,
null is a literal for a reference type.
- 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.
- Example:

class Student {

String name; // name has the default value null

int age; // age has the default value 0

boolean isScienceMajor; // isScienceMajor has default value false

char gender; // gender has default value '\u0000'

class TestStudent {

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

7. Using Classes from the Java Library


7.1 The “Date” Class
- Java provides a system-independent encapsulation of date and time in the
java.util.Date class
- The no-arg constructor in the Date class to create an instance for the current date
and time
- The getTime() method to return the elapsed time in milliseconds since January 1,
1970, GMT
- The toString() method to return the date and time as a string.
- Example:
java.util.Date date = new java.util.Date();
System.out.println("The elapsed time since Jan 1, 1970 is " + date.getTime() + "
milliseconds");
System.out.println(date.toString());
Output:
The elapsed time since Jan 1, 1970 is 1324903419651 milliseconds Mon Dec 26
07:43:39 EST 2011
7.2 The “Random” Class
- The java.util.Random can generate random numbers such as int, long, double,
float and Boolean value

- When creating Random object, we have to specify a seed or use the default seed.
A seed is a number used to initialize a random number generator.
- If two Random objects have the same seed, they will generate identical
sequences of numbers.
- Example:
Random generator1 = new Random(3);
System.out.print("From generator1: ");
for (int i = 0; i < 10; i++)
System.out.print(generator1.nextInt(1000) + " ");
Random generator2 = new Random(3);
System.out.print("\nFrom generator2: ");
for (int i = 0; i < 10; i++)
System.out.print(generator2.nextInt(1000) + " ");
Output:
From generator1: 734 660 210 581 128 202 549 564 459 961
From generator2: 734 660 210 581 128 202 549 564 459 961
7.3 The “Point2D” Class
- Java API has a convenient Point2D class in the javafx.geometry package for
representing a point in a two-dimensional plane.

- Example:
1 import java.util.Scanner;
2 import javafx.geometry.Point2D;
3
4 public class TestPoint2D {
5 public static void main(String[] args) {
6 Scanner input = new Scanner(System.in);
7
8 System.out.print("Enter point1's x-, y–coordinates: ");
9 double x1 = input.nextDouble();
10 double y1 = input.nextDouble();
11 System.out.print("Enter point2's x-, y–coordinates: ");
12 double x2 = input.nextDouble();
13 double y2 = input.nextDouble();
14
15 Point2D p1 = new Point2D(x1, y1);
16 Point2D p2 = new Point2D(x2, y2);
17 System.out.println("p1 is " + p1.toString());
18 System.out.println("p2 is " + p2.toString());
19 System.out.println("The distance between p1 and p2 is " +
p1.distance(p2));
20 System.out.println("The midpoint between p1 and p2 is " +
p1.midpoint(p2).toString());
21 }
22 }
Output:

8. Static Variables, Constants, and Methods


- A static variable is shared by all objects of the class. A static method cannot
access instance members (i.e., instance data fields and methods) of the class.
- An instance variable is tied to a specific instance of the class; it is not shared
among objects of the same class.
- Static variables store values for the variables in a common memory location.
- If one object changes the value of a static variable, all objects of the same class
are affected
- Example:

(Explain: 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 Circle class defines the instance
variable radius and the static variable numberOfObjects, the instance methods
getRadius, setRadius, and getArea, and the static method
getNumberOfObjects.) (Static variables and methods are underlined)
- Instance variables belong to the instances and have memory storage independent
of one another. Static variables are shared by all the instances of the same class
- To declare a static variable or define a static method, put the modifier static in
the variable or method declaration.
- Example:
static int numberOfObjects;
static int getNumberObjects() {
return numberOfObjects;
}
- Constants in a class are shared by all objects of the class and should be declared
as final static.
Example:
final static double PI = 3.14159265358979323846;

- For example, the following code is wrong.


1 public class A {
2 int i = 5;
3 static int k = 2;
4
5 public static void main(String[] args) {
6 int j = i; // Wrong because i is an instance variable
7 m1(); // Wrong because m1() is an instance method
8}
9
10 public void m1() {
11 // Correct since instance and static variables and methods
12 // can be used in an instance method
13 i = i + k + m2(i, k);
14 }
15
16 public static int m2(int i, int j) {
17 return (int)(Math.pow(i, j));
18 }
19 }

The correct one:


1 public class A {
2 int i = 5;
3 static int k = 2;
4
5 public static void main(String[] args) {
6 A a = new A();
7 int j = a.i; // OK, a.i accesses the object's instance variable
8 a.m1(); // OK, a.m1() invokes the object's instance method
9 }
10
11 public void m1() {
12 i = i + k + m2(i, k);
13 }
14
15 public static int m2(int i, int j) {
16 return (int)(Math.pow(i, j));
17 }
18 }

9. Visibility Modifiers
- Visibility modifiers can be used to specify the visibility of a class and its
members
- The public visibility modifier can be used for classes, methods, and data fields to
denote they can be accessed from any other classes.
- A private method or data is accessible only inside the class
- 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 example illustrates how a public, default, and private data field or method in
class C1 can be accessed from a class C2 in the same package, and from a class C3
in a different package.
=> The private modifier restricts access to its defining class, the default modifier
restricts access to a package, and the public modifier enables unrestricted access.
- If a class is not defined as public, it can be accessed only within the same
package.
C1 can be accessed from C2, but not from C3

- An object can access its private members if it is defined in its own class.

10. Data Field Encapsulation


- Is defined as the wrapping up of data under a single unit
- The variables or data of a class are hidden from any other class and can be
accessed only through any member function of their class in which they are
declared
- Example of encapsulation (đọc để biết thôi): Consider a real-life example of
encapsulation, in a company, there are different sections like the accounts section,
finance section, sales section, etc. The finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the
sales section handles all the sales-related activities and keeps records of all the
sales. Now there may arise a situation when for some reason an official from the
finance section needs all the data about sales in a particular month. In this case,
he is not allowed to directly access the data of the sales section. He will first have
to contact some other officer in the sales section and then request him to give the
particular data. This is what encapsulation is. Here the data of the sales section
and the employees that can manipulate them are wrapped under a single name
“sales section”.
- A private data field cannot be accessed by an object from outside the class that
defines the private field
- However, a client often needs to retrieve and modify a data field:

+ 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 has the following signature:
public returnType getPropertyName()
+ If the returnType is boolean, the getter method should be defined as follows by
convention:
public boolean isPropertyName()
- A setter method has the following signature:
public void setPropertyName(dataType propertyValue)

11. Passing Objects to Methods


- Like passing an array, passing an object is actually passing the reference of the
object
- The difference between passing a primitive-type value and passing a reference
value
The program passes a Circle object myCircle and an integer value from n to
invoke printAreas(myCircle, n) (line 10), which prints a table of areas for radii 1,
2, 3, 4, and 5, as presented in the sample output.
When passing an argument of a primitive data type, the value of the argument is
passed. In this case, the value of n (5) is passed to times. Inside the printAreas
method, the content of times is changed; this does not affect the content of n
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
Summary: All parameters are passed to methods using pass-by-value. For a
parameter of a primitive type, the actual value is passed; for a parameter of a
reference type, the reference for the object is passed

12. Array of Objects


- An array can hold objects as well as primitive-type values. 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.

- In an array of objects, an element of the array contains a reference to an object


- Example:
Output:
The program invokes createCircleArray() (line 8) to create an array of five circle
objects. Several circle classes were introduced in this chapter

13. Immutable Objects and Classes


- Immutable objects are objects whose contents cannot be changed once the objects
have been created.
- The class of the immutable objects are 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
- For a class to be immutable, it must meet the following requirements:
+ All data fields must be private.
+ There can’t be any mutator methods for data fields.
+ No accessor methods can return a reference to a data field that is mutable.

14. The Scope of Variables


- Instance and static variables in a class are referred to as the class’s variables or
data fields. A variable defined inside a method is referred to as a local variable.
- The scope of instance and static variables is the entire class, regardless of where
the variables are declared.
- A class’s variable can only be declared once, but the same variable name can be
declared in a method many times in different nonnesting blocks.

15. The “this” Reference


- The this keyword is the name of a reference that an object can use to refer to
itself.
- However, the this reference is needed to reference a data field hidden by a
method or constructor parameter, or to invoke an overloaded constructor.

15.1 Using “this” to Reference Data Fields


- The keyword this refers to the calling object that invokes the 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. The line F.k = k means the value in
parameter k is assigned to the static data field k of the class, which is shared by all
the objects of the class)
15.2 Using “this” to Invoke a Constructor:
- The this keyword can be used to invoke another constructor of the same class.

The line this(1.0) in the second constructor invokes the first constructor with a
double value argument

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy