0% found this document useful (0 votes)
44 views24 pages

OOP Chapter II

Uploaded by

abrhamashenafi3
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)
44 views24 pages

OOP Chapter II

Uploaded by

abrhamashenafi3
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
You are on page 1/ 24

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: www.davidtechnotips.com
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.
 A class is the blueprint from which objects are generated. 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.
 Object-oriented programming therefore consists of
defining one or more classes that may interact with each
other.
 ..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.
4 Object and classes
 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.
 Class
 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.
 A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space
 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.
5 Object and classes
 We can think of the class as a sketch (prototype) of a house. It contains all the details about
the floors, doors, windows, etc. Based on these descriptions we build the house. House is the
object.
 In one program we may have many classes, as we would probably wish to generate many
kinds of objects.
 Object-oriented programming therefore consists of defining one or more classes that may
interact with each other;
 To exploit the full power of object-orientation requires us to use an object-oriented
programming language e.g: C++, SmallTalk, Eiffel, C#, Java.
Objects
6

 Object can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
 An object has three characteristics:
•State: represents the data (value) of an object.
•Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw, etc.
•Identity: An object identity is typically implemented
via a unique ID. The value of the ID is not visible to the
external user. However, it is used internally by the JVM
to identify each object uniquely.
Class
7

 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
Syntax to declare a class:
8
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
System.out.println("Working of Braking"); classes.
} private - means it cannot be accessed by other
classes.
Creating, Instantiating and using objects
9

 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.
10

We then use the object to access the


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

 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: Student.java
class Student{
//defining fields
int id;//field or data member or instance variable //Printing values of the object
String name; System.out.println(s1.id);//accessing member
//creating main method inside the Student class through reference variable
public static void main(String args[]){ System.out.println(s1.name);
//Creating an object or instance }
output
Student s1=new Student();//creating an object }
0
of Student null
12

 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.
13 //Java Program to demonstrate having the main method in another class
//Creating Student class. File: TestStudent1.java
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
System.out.println(s1.id);
System.out.println(s1.name);
}
}
14

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
15

 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 TestStudent2.java
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=132; output
s1.name="Samuel"; 132 Samuel
//printing members with a white space
System.out.println(s1.id+" "+s1.name);
} }
We can also create multiple objects and store information in it through reference variable.
class Student{ // File: TestStudent3.java
16 int id;
String name; }
class TestStudent3 {
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=150;
s1.name="Mengistu";
s2.id=155; output
s2.name="Zewudineh"; 150 Mengistu
//Printing data 155 Zewudineh
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
} }
2) Object and Class Example: Initialization through method

17

 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
18

 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
System.out.print("The maximum number is: " + Math.max(20,10));
}
}
Method declaration
19

 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.
20

 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.
21

 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

22
 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: TestStudent4.java
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;
s1.insertRecord(102,“Meron");
name=n;
s2.insertRecord(202,“Bekele");
}
s1.displayInformation();
void displayInfo(){
s2.displayInformation();
System.out.println(rollno+" "+name);
}
} output
}
} 102 Meron
202 Bekele
3) Object and Class Example: Initialization through a constructor

23

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; System.out.println("Id Name Salary");
name=n; e1.insert(10,"Ayele",5000);
salary=s; e2.insert(11,"Bekelech",6000);
} e3.insert(12,"Mola",6500);
void display(){ e1.display(); output
System.out.println(id+" "+name+" "+salary); e2.display(); Id Name Salary
} e3.display(); 10 Ayele 5000
} } 11 Bekelech 6000
} 12 Mola 6500
24 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.
End of Chapter 2

You might also like