0% found this document useful (0 votes)
2 views29 pages

OOP Chapter II

The document outlines the course content for Object Oriented Programming (CoSc2051) at Wolaita Sodo University, focusing on key concepts such as classes, objects, methods, and constructors in Java. It explains the relationship between classes and objects, using analogies like a car's accelerator pedal to illustrate how methods operate within classes. Additionally, it covers the syntax for declaring classes, creating objects, and initializing them through various methods, emphasizing the principles of encapsulation and access modifiers.

Uploaded by

wondebelete92
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

OOP Chapter II

The document outlines the course content for Object Oriented Programming (CoSc2051) at Wolaita Sodo University, focusing on key concepts such as classes, objects, methods, and constructors in Java. It explains the relationship between classes and objects, using analogies like a car's accelerator pedal to illustrate how methods operate within classes. Additionally, it covers the syntax for declaring classes, creating objects, and initializing them through various methods, emphasizing the principles of encapsulation and access modifiers.

Uploaded by

wondebelete92
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Wolaita Sodo University

School of Informatics
Department of Computer Science

Object Oriented Programming (CoSc2051)

Compiled by Dawit Uta. (M. Tech.)


Computer Science Department, WSU
website address: [Link]
Course outline: Chapter 2 Objects and Classes
2

 2.1. Defining a class  2.3.4. Comparing and Identifying Objects


 2.2. Creating an Object  2.3.5. Destroying Objects
 2.3. Instantiating and using objects  2.3.6. Enumerated Types
 2.3.1. Printing to the Console  2.4. Instance fields
 2.3.2. Methods and Messages  2.5. Constructors and Methods
 2.3.3. Parameter Passing  2.6. Access Modifiers
 2.7. Encapsulation
3
Object and classes
 In the object-oriented approach, methods and the data they act upon are grouped together
into one unit - an object.
 An object is an instance of the class.
 Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical.
 A class is the blueprint from which objects are generated. Class doesn't consume any space
 The class is one of the basic concepts of OOPs which is a group of similar entities. It is only
a logical component and not the physical entity.
 Lets understand this one of the OOPs Concepts with example, if you had a class called
“Expensive Cars” it could have objects like Mercedes, BMW, Toyota, etc.
 Its properties(data) can be price or speed of these cars. While the methods may be performed
with these cars are driving, reverse, braking etc.
4
Object and classes
 Let’s begin with a simple analogy to help you understand classes and their contents. Suppose
you want to drive a car and make it go faster by pressing down on its accelerator pedal.
 What must happen before you can do this? Well, before you can drive a car, someone has to
design it. A car typically begins as engineering drawings, similar to the blueprints used to
design a house.
 These engineering drawings include the design for an accelerator pedal to make the car go
faster. The pedal “hides” from the driver the complex mechanisms that actually make the car
go faster, just as the brake pedal “hides” the mechanisms that slow the car and the steering
wheel “hides” the mechanisms that turn the car.
 This enables people with little or no knowledge of how engines work to drive a car easily.
 Unfortunately, you cannot drive the engineering drawings of a car. Before you can drive a
car, the car must be built from the engineering drawings that describe it.
5
Object and classes
A completed car has an actual accelerator pedal to make the car go faster, but
even that’s not enough the car won’t accelerate on its own, so the driver must
press the accelerator pedal.
Now let’s use our car example to introduce the key programming concepts of
this section.
Performing a task in a program requires a method. The method describes the
mechanisms that actually perform its tasks. The method hides from its user the
complex tasks that it performs, just as the accelerator pedal of a car hides from
the driver the complex mechanisms of making the car go faster.
In Java, we begin by creating a program unit called a class to house a method,
just as a car’s engineering drawings house the design of an accelerator pedal.
6
Object and classes
In a class, you provide one or more methods that are designed to perform the
class’s tasks. For example, a class that represents a bank account might contain
one method to deposit money to an account, another to withdraw money from an
account and a third to inquire what the current balance is.
That is one reason Java is known as an object-oriented programming language.
When you drive a car, pressing its gas pedal sends a message to the car to
perform a task that is, make the car go faster.
Similarly, you send messages to an object, each message is known as a method
call and tells a method of the object to perform its task.
7
Object and classes
Thus far, we’ve used the car analogy to introduce classes, objects and methods.
In addition to a car’s capabilities, a car also has many attributes, such as its
color, the number of doors, the amount of gas in its tank, its current speed and
its total miles driven (i.e., its odometer reading).
The only necessary thing is the type of message accepted and the type of
response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.
 An object contains an address and takes up some space in memory.
Objects can communicate without knowing the details of each other's data or
code.
8
Object and classes
The first example presents a GradeBook class with one method that simply
displays a welcome message when it is called. We then see how to create an
object of that class and call the method so that it displays the welcome
message.
 The GradeBook class declaration
contains a displayMessage method
(lines 7– 10) that displays a message
on the screen. Line 9 of the class
performs the work of displaying the
message.
 Recall that a class is like a blueprint
we’ll need to make an object of this
class and call its method to get line 9
to execute and display its message.
9
Creating, Instantiating and using objects
10 Creating, Instantiating and using objects
 The class above contains only a main method, which is typical of many classes that begin an
application’s execution. Lines 7–14 declare method main. Recall from Chapter 1 that the
main header must appear as shown in line 7; otherwise, the application will not execute.
 A key part of enabling the JVM to locate and call method main to begin the application’s
execution is the static keyword (line 7), which indicates that main is a static method. A static
method is special because it can be called without first creating an object of the class in
which the method is declared.
 In this application, we’d like to call class GradeBook’s displayMessage method to display
the welcome message in the command window. Typically, we cannot call a method that
belongs to another class until you create an object of that class, as shown in line 10. We
begin by declaring variable myGradeBook.
11 Creating, Instantiating and using objects
 Variable myGradeBook is initialized with the result of the class instance creation expression
new GradeBook().
 Keyword new creates a new object of the class specified to the right of the keyword (i.e.,
GradeBook).
 GradeBook() is similar with a class name called a constructor, which is similar to a method,
but is used only at the time an object is created to initialize the object’s data.
Creating, Instantiating and using objects
12

 A class in Java can contains:


 Fields: a Java field is a variable inside a class.
 Methods: is a set of instructions that can accept parameters, or
values to perform a given task. Both Java fields and methods have
a type, or the type of data they contain (such as an int or double).
 Constructors: it is a special method that is used to created and
initialize objects.
 Block: is a group of statements (zero or more) that is enclosed in
curly braces { } .
 Nested class and interface: A class or an interface, that is
declared within another class or interface
Creating, Instantiating and using objects
13 Syntax to declare a class:
class class_name {  In this example, we have created a class
field; named Bicycle, which contains a field
named gear and a method
method;
named braking().
}  Here we have used keywords private
Example: Create a Bicycle class in Java and public. These are known as access
modifiers.
class Bicycle {
Access modifiers: are used to set the
// state or field accessibility (visibility) of classes, interfaces,
private int gear = 5; variables, methods, constructors, data
// behavior or method members, and the setter methods.
public void braking() { public - This means it can be accessed by other
[Link]("Working of Braking"); classes.
} private - means it cannot be accessed by other
classes.
Creating, Instantiating and using objects
14

 Object is an instance of a class. For example, suppose Bicycle is a class then sportsBicycle,
touringBicycle, etc can be considered as objects of the class.
 Creating an Object using constructor
 Here is how we can create an object of a class.
className object = new className();
// for Bicycle class
Bicycle sportsBicycle = new Bicycle();
Bicycle touringBicycle = new Bicycle();
 We have used the new keyword along with the constructor of the class to create an object
sportsBicycle and touringBicycle.
 Constructors are similar to methods and have the same name as the class. For
example, Bicycle() is the constructor of the Bicycle class.
15

We then use the object to access the


field and method of the class.
•[Link] - access the Example: Create class Main, object called
field gear "myObj" and print the value of x:
•[Link]() - access public class Main {
the method braking() int x = 16;
public static void main(String[] args) {
Main myObj = new Main();//constructor
[Link](myObj.x);
}
}
Example 2
16

 we have created a Student class which has two data members id and name.
 We are creating the object of the Student class by new keyword and printing
the object's value. Here, we are creating a main() method inside the class.
//Defining a Student class. File: [Link]
class Student{
//defining fields
int id;//field or data member or instance variable //Printing values of the object
String name; [Link]([Link]);//accessing member
//creating main method inside the Student class through reference variable
public static void main(String args[]){ [Link]([Link]);
//Creating an object or instance }
output
Student s1=new Student();//creating an object }
0
of Student null
17

 Object and Class Example: main outside the class

 In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main()
method in another class.

 We can have multiple classes in different Java files or single Java file.

 If you define multiple classes in a single Java source file, it is a good idea to save the file
name with the class name which has main() method.
18 //Java Program to demonstrate having the main method in another class
//Creating Student class. File: [Link]
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
output
public static void main(String args[]){
0
Student s1=new Student();
null
[Link]([Link]);
[Link]([Link]);
}
}
19

3 Ways to initialize object


There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
1) Object and Class Example: Initialization through reference
20

 Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable. //Save as [Link]
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
[Link]=132; output
[Link]="Samuel"; 132 Samuel
//printing members with a white space
[Link]([Link]+" "+[Link]);
} }
We can also create multiple objects and store information in it through reference variable.
class Student{ // File: [Link]
21 int id;
String name; }
class TestStudent3 {
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
[Link]=150;
[Link]="Mengistu";
[Link]=155; output
[Link]="Zewudineh"; 150 Mengistu
//Printing data 155 Zewudineh
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
} }
2) Object and Class Example: Initialization through method

22

 First of all let’s see in detail about the method in java.


 A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation.
 It is used to achieve the reusability of code. We write a method once and use it many times. We
do not require to write code again and again.
 It also provides the easy modification and readability of code, just by adding or removing a
chunk of code.
 The method is executed only when we call or invoke it. The most important method in Java is
the main() method
23

 There are two types of methods in Java: predefined and user defined.
 In Java, predefined methods are the method that is already defined in the Java class libraries.
 It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point.
 Some pre-defined methods are length(), equals(), compareTo(), sqrt(), max() etc.
 The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Example
public class Demo {
public static void main(String[] args) {
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](20,10));
}
}
Method declaration
24

 The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments.
 It has four components that are known as method header, as we have shown in the following
figure.
25

 Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
 Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:
 Public: The method is accessible by all classes when we use public specifier in our
application.
 Private: When we use a private access specifier, the method is accessible only in the classes
in which it is defined.
 Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
 Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
26

 Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
 Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.
 Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
 Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
2) Object and Class Example: Initialization through method

27
 Now we are creating the two objects of Student class and initializing the value to these objects
by invoking the user defined insertRecord, method.
 Here, we are displaying the state (data) of the objects by invoking the displayInfo() method.
class Student{ //File: [Link]
class TestStudent4{
int rollno;
public static void main(String args[]){
String name;
Student s1=new Student();
void insertRecord(int r, string n){
Student s2=new Student();
rollno=r;
[Link](102,“Meron");
name=n;
[Link](202,“Bekele");
}
[Link]();
void displayInfo(){
[Link]();
[Link](rollno+" "+name);
}
} output
}
} 102 Meron
202 Bekele
3) Object and Class Example: Initialization through a constructor

28

class Employee{ public class TestEmployee {


int id; public static void main(String[] args) {
String name; Employee e1=new Employee();
float salary; Employee e2=new Employee();
void insert(int i, String n, float s) { Employee e3=new Employee();
id=i; [Link]("Id Name Salary");
name=n; [Link](10,"Ayele",5000);
salary=s; [Link](11,"Bekelech",6000);
} [Link](12,"Mola",6500);
void display(){ [Link](); output
[Link](id+" "+name+" "+salary); [Link](); Id Name Salary
} [Link](); 10 Ayele 5000
} } 11 Bekelech 6000
} 12 Mola 6500
29 Destroying Objects
 Java Destructor: when we create an object of the class it occupies some space in the memory (heap).
 If we do not delete these objects, it remains in the memory and occupies unnecessary space that is not
upright from the aspect of programming.
 To resolve this problem, we use the destructor. Java use the finalize() method as a destructor.
 The destructor is the opposite of the constructor. The constructor is used to initialize objects while
the destructor is used to delete or destroy the object that releases the resource occupied by the object.
 Remember that there is no concept of destructor in Java. In place of the destructor, Java provides the
garbage collector that works the same as the destructor.
 The garbage collector is a program (thread) that runs on the JVM. It’s automatically called to delete
the unused objects (objects that are no longer used) and free-up the memory.
 The programmer has no need to manage memory, manually. It can be error-prone, vulnerable, and may
lead to a memory leak.

You might also like