[go: up one dir, main page]

0% found this document useful (0 votes)
5 views9 pages

IT oop ch-3

Chapter Three discusses the principles of classes and objects in Java's object-oriented programming. It covers the design process, advantages of using classes, modeling real-world problems, and the differences between classes and objects. Additionally, it explains constructors, their types, and provides examples of defining and using classes and objects in Java.

Uploaded by

solomontsegaw125
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)
5 views9 pages

IT oop ch-3

Chapter Three discusses the principles of classes and objects in Java's object-oriented programming. It covers the design process, advantages of using classes, modeling real-world problems, and the differences between classes and objects. Additionally, it explains constructors, their types, and provides examples of defining and using classes and objects in Java.

Uploaded by

solomontsegaw125
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/ 9

Chapter Three

Classes and Objects


3.1 Overview
When we face with a problem domain; we have to architect/design a solution. Since Java is an object-
oriented language, we should perform an object-oriented design. In this process, you will end up with
classes, objects, attributes, and behaviors/methods.
Object-oriented design process involves the following three tasks:
➢ Dividing the problem domain into types of objects/classes,
➢ Modeling the relationships between classes
➢ Modeling the attributes and behaviors /methods of each type.
These tasks are not listed in any particular order. Most likely, you will perform these tasks iteratively
throughout the design process.
In an object-oriented design:
- You identify the fundamental objects of the problem domain, the "things" involved.
- then classify the objects into types by identifying groups of objects that have common
characteristics and behaviors.
The types of objects you identify in the problem domain become "types" in your solution. The program
you write will create and manipulate objects of these types. The fundamental task of abstraction in an
object-oriented design is to identify classes and objects in the problem domain and then to identify
attributes and methods.
➢ Classes combine data and methods.
➢ A class defines a data type.
➢ Advantages: Classes correspond to concepts in the problem domain
➢ Classes reduce complexity by increasing coherence.
Class = data + methods. (classes are the collections of data and methods related to a system)

Everything (data and methods) in Java is contained in classes. So far you've been using classes to hold
methods (main and perhaps a few other static methods). These methods use local variables, which are
completely private to the method, and which disappear when the method returns.

3.2. Advantage of using “Classes”


➢ Classes used to model problems.
One advantage of encapsulating data and methods in a class is to make programming objects that reflect
"objects" in the problem domain. If your problem deals with sales, then you will very likely have classes
called Order and Product.

Object oriented programming in Java---------------------chapter three Page 1


➢ Classes used to reduce complexity.
Another advantage of classes is reducing complexity. Complexity limits the size and reliability of programs.
Complexity is reduced by increasing cohesion (putting things together that belong together) and
reducing coupling (interconnections).

3.3 Modeling real world problems:


The main task of OOP is to modeling the real world problem using classes and objects. Classes and objects
are models that used to represent the real world problem that supposed to be solved. A model is a
representation of simple important aspects of the real world. Model used in software development like,
representation of input, objects, object interaction and classes. Abstraction is the main source for modeling.
These models represent classes and objects. Thus, classes and objects are a representation of reality,
abstracted from the complex real world.
Finding classes and objects
➢ The first step in finding classes and objects is: studying the problem domain.
➢ Classes and objects should initially emerge from the problem domain itself.
➢ we should prepare to spend a good deal of time in investigation.
➢ Observe first hand documents by working with the end users.
➢ Take the specialist in that area and problem domain experts.
➢ Look for previous results on similar problem domain.
➢ Construct a prototype – simple skeleton of real system, using classes, objects and including
expected interactions between.
After the above activities are done, the classes and objects can be used to: identify the potential/necessary
attribute or fields and to identify methods required to access its data.

Examples of systems that need object oriented solution


➢ Example 1: Consider Cost Sharing System, use abstraction feature and list possible classes,
attributes, and methods
➢ Example 2: Consider Dormitory System, use abstraction technique and list possible classes,
attributes, and methods.
➢ Example 3: Do the same as above for Car Registration System.

Object oriented programming in Java---------------------chapter three Page 2


In object oriented concept class is similar to database table. If you are familiar with databases, a class is
very similar to a table definition. In Java programming, a class is basically user-defined data types which
act as a template for creating objects of the identical type. It represents the common properties and actions
(functions) of an object. In other words, a class can also be defined as "a class is a group of objects which
are common to all objects of one type".

Real-time example 1:
Let us consider two objects Samsung Galaxy S4 and iPhone. Suppose Samsung Galaxy S4 have some
properties like width="6.98 cm", height="13.6 cm", OS="Android", brand="Samsung", price="1000$"
and Actions are call(), sendMessage(), browser(), share().
Now, suppose iPhone has some properties such as width="5.86 cm", height="12.3 cm", OS="iOS",
brand="Apple", price="1200$" and actions are call(), sendMessage(), browse(), share().

Both objects have some different properties and actions but the type is the same "Phone". This is the
class. i.e the name of the class is "Phone".

Real-time example 2:
Consider two objects one boy and one girl. The boy has some properties like hairColor="black",
eyeColor="black", skinColor="Fair", height="5.10 inch", weight="65 kg" and actions are read(), play(),
sleep(), walk().
Now, The girl has some properties like hairColor="Brown", eyeColor="brown", skinColor=" white",
height="5.4 inch", weight="50 kg" and actions are read(), play(), sleep(), walk(). but the type of both is
the same. i,e Person. So the class name is 'Person'.

A class has two main sections: Private and public


- A private part can only be accessible by member methods (by all methods defined inside the class).
- A public part can be used by other methods and classes outside the given class.

Examples of defining Classes and Objects in java


Example 1: it shows how to define private and public sections of a class
public class Myclass {
Private int x; // accessed only inside Myclass
Public float y; //can be accessed outside Myclass
Private method1 ( ) {} //can’t access data outside this class
Public method2 ( ) { } //can access data from other class
}

Object oriented programming in Java---------------------chapter three Page 3


Example 2: Here is the class again that represents information about a student.
// Purpose: Information about a student public
class Student {
public String fName; // First name
public String lName; // Last name
private int id; // Student id
}
3.4. Creating new objects inside a class
A class defines what fields an object will have when it's created. When a new Student object is created, a block
of memory is allocated, which is big enough to hold these three fields -- as well as some extra overhead that all
objects have. Use the keyword “new” to create objects;
Syntax: ClassName objectName = new ClassName ();
Here in the above line; the ClassName represents the objectType();

Example; Student stud = new Student();


// Creating Student object name as stud which is Student type with new operator.
Or we can write in two line in the following way:
Student stud;
stud=new Student ( );
To create a new object, write the word “new” followed by the name of the class, followed by parentheses.

Access public fields with dot notation


All public fields can be referenced using dot notation. To reference a field, write the object name, then a dot, then
the field name or method name.
Student stud; // Declare a variable to hold a Student object.
stud = new Student(); // Create a new Student object with default values.
stud.firstName = "Rishan"; // Set values of the fields.
stud.lastName = "Mezgeb";
stud.id=1234;

A class definition is a template for creating objects. A class defines which fields an object has in it. We need to use
new to create a new object from the class by allocating memory and assigning a default value to each field.

Object oriented programming in Java---------------------chapter three Page 4


Difference between Class and Object in Java
1. A class is a user-defined data type whereas an object is an instance of the class data type.
2. A class generates objects whereas an object gives life to a class.
3. Classes do not occupy memory location but objects occupy memory location.
4. Classes cannot be manipulated due to not available in the memory location but objects can be manipulated.
3.5. Constructor
A constructor is a special initialization method that is called automatically whenever an instance of a class is created.
The constructor member method has, the same name as the corresponding class and has no return value
specification. The Java run-time system makes sure that the constructor of a class is called when instantiating an
object.
Constructor is special method having the following properties.
• Automatically invoked when a class instance is created using the new operator
• Has same name as the class
• Has no return type
• Java creates a default constructor if no constructor has been explicitly written for a class.
Constructors are used to initialize the data members of the class. If we have data members
that must be initialized, we must have a constructor
In java we have two types of constructors; default constructor and parameterized constructor.
a. Default (Non-Parameterized) constructors
This helps to initialize objects using default values, let us look at the following example.
public class Employee{
String empName;
String address;
int id;
public Employee( ) // Default constructor
{ empName “ ”; address = “
”;
int=0;
}
} //end class

The constructor Employee () is a default or a non-parameterized constructor, because it doesn’t use parameters.
Default parameter is used to initialize the object with default value.

Object oriented programming in Java---------------------chapter three Page 5


b. Parameterized constructors
The parameterized constructors can accept values into the constructor that has different parameters in the
constructor. The value would be transferred from the main ( ) method to the constructor either with direct values
or through variables.

Parameterized Constructor has parameter list to receive arguments for populating the instance attributes. When we
create a new instance (a new object) of a class using the new keyword, a constructor for that class is called.
Constructors are used to initialize the instance variables (fields) of an object and constructors are similar to methods,
but with some important differences.
➢ Constructor name is class name i.e., they must have the same name as the class.
➢ Default constructor. If you don't define a constructor for a class, a default (parameterless) constructor is
automatically created by the compiler. The default constructor calls the default parent constructor (super ( ))
and initializes all instance variables to default value (zero for numeric types, null for object references, and false
for Booleans).
Differences between methods and constructors
• There is no return type given in a constructor signature (header). The value is this object itself so there is no
need to indicate a return value.
• There is no return statement in the body of the constructor. There can be more than one constructor in a class,
distinguished by their parameters. When the class is initialized, Java will call the right constructor with matching
arguments and type.
Example 1: //without constructors
public class Circle {
public int x, y; // centre of the circle
public int r; // radius of circle
//Methods to return circumference and area
public double circumference()
{ return 2*3.14*r; }
public double area()
{ return 3.14 * r * r; }
public static void main(String args[]) {
Circle C; // creating reference
C = new Circle(); // creating object
C.x = 10; // assigning value to data field

Object oriented programming in Java---------------------chapter three Page 6


C.y = 20;
C.r = 5;
double area = C.area(); // invoking method
double circumf = C.circumference();
System.out.println("Radius="+C.r+" Area="+area);
System.out.println("Radius="+C.r+" Circumference ="+circumf);
}}

Example 2: // Write the above code using constructors


public class Circle {
public int x, y; // centre of the circle
public int r; // radius of circle
Circle( ){
x=0; y=0; r=0;
}
Circle(int valx , int valy , int valr) {
x=valx; y=valy ; r=valr;
}
//Methods to return circumference and area
Public Class circle {
public double circumference( )
{
return 2*3.14*r;
}
Public double area()
{
return 3.14*r*r;
}
public static void main (String args[]){
Circle c1=new Circle();
System.out.println("The value of x is " + c1.x);
System.out.println("The value of yis "+ c1.y);
System.out.println("The value of r is " + c1.r);

Object oriented programming in Java---------------------chapter three Page 7


Circle c2=new Circle(4,2,5);
System.out.println("The value of x is " + c2.x);
System.out.println("The value of y is " + c2.y);
System.out.println("The value of r is " + c2.r);
System.out.println("Area of c2 is" +c2.area( ));
System.out.println("Circumference of c2 is "+c2. circumference( ));
}
}
Example 3: It contains two constructors - Default and Parameterized. This example is about a
polygon, Cube
public class Cube {
int length, width, height;
public int getVolume()
{ return (length *width * height); }
Cube ( ) {
length = 0;
width = 0;
height = 0;
}
Cube (int L, int W, int H) {
length = L;
width = W;
height = H;
}
public static void main(String[] args) {
Cube cubeObj1, cubeObj2;
cubeObj1 = new Cube ( );
cubeObj2 = new Cube (10, 10, 10);
System.out.println("Volume of Cube is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube is : " + cubeObj2.getVolume());
}}
If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default
constructor will be a compile time error if an explicit default constructor is not provided in such a case.

Object oriented programming in Java---------------------chapter three Page 8


Summary
➢ Constructor is a special method that gets invoked “automatically” at the time of object creation.
➢ Constructor is normally used for initializing objects with default values unless different values are
supplied.
➢ Constructor has the same name as the class name.
➢ Constructor cannot return values.
➢ A class can have more than one constructor as long as they have different signature (i.e., different input
arguments syntax).

Object oriented programming in Java---------------------chapter three Page 9

You might also like