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

OOP: Classes, Objects, and Constructors

This document discusses object-oriented programming concepts in Java, including: 1. Classes combine data (attributes) and methods, and define a data type. Everything in Java is contained within classes. 2. Designing solutions by identifying real-world objects and classes, and modeling their relationships, attributes, and behaviors. 3. Constructors are special methods that initialize new objects and are automatically called when objects are created using the new operator. Constructors can be default or parameterized.

Uploaded by

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

OOP: Classes, Objects, and Constructors

This document discusses object-oriented programming concepts in Java, including: 1. Classes combine data (attributes) and methods, and define a data type. Everything in Java is contained within classes. 2. Designing solutions by identifying real-world objects and classes, and modeling their relationships, attributes, and behaviors. 3. Constructors are special methods that initialize new objects and are automatically called when objects are created using the new operator. Constructors can be default or parameterized.

Uploaded by

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

Object Oriented Programming in Java

Chapter Two

More on Classes and Objects


2.1 Overview
When you faced with a problem domain and you have to architect a solution. Given that Java is
an object-oriented language, you 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.
- You 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.

o Classes combine data and methods.


o A class defines a data type.
o Advantages: Classes correspond to concepts in the problem domain.
o Classes reduce complexity by increasing coherence.

Class = data + methods.

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.

DMU IT Dep’t Page 1


Object Oriented Programming in Java
2.2 Advantage of thinking a solution in terms of “Classes”

Classes used to model problem.


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'll very likely
have classes called Order and Product.

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

2.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.

 You 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 this is done, the classes and objects can be used to

1. Identify the potential/necessary attribute or fields

2. Identify methods required to access its data.

DMU IT Dep’t Page 2


Object Oriented Programming in Java

Class name
List of Attributes
List of Methods

Examples of systems that need OO 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. Do the same for Car Registration System.

Class is similar to database table. If you are familiar with databases, a class is very similar to a
table definition.

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
}

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

DMU IT Dep’t Page 3


Object Oriented Programming in Java
private int id; // Student id
}
2.4 Use new operator to create a new object

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.

Student stud;
stud = new Student(); // Create Student object with new operator.
Or we can write in one line in the following way:
Student stud=new Student ( );

To create a new object, write new followed by the name of the class, followed by parentheses.
Later we'll see that we can specify arguments in the parentheses when creating new objects.

Access public fields with dot notation

All public fields can be referenced using dot notation (later we'll see better ways to access and
set fields). 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.
[Link] = "Rishan"; // Set values of the fields.
[Link] = "Mezegeb";
[Link] = 1234;

A class definition is a template for creating objects. A class defines which fields an object has in
it. You need to use new to create a new object from the class by allocating memory and assigning
a default value to each field. A little later you will learn how to write a constructor to control the
initialization.

2.5 Constructor
- Constructor can be Default and Parameterized

DMU IT Dep’t Page 4


Object Oriented Programming in Java
A constructor is a special initialization method that is called automatically whenever an instance
of a class is created. The constructor member method has, by definition, the same name as the
corresponding class. The constructor 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 Method
 Automatically invoked when a class instance is created using the new operator
o Has same name as the class
o Has no return type
o 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

Default (Non-Parameterized) constructors


Used 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

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 you 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. Constructors are similar to methods, but with some important differences.

DMU IT Dep’t Page 5


Object Oriented Programming in Java
 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 (parameter less)
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 aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;

DMU IT Dep’t Page 6


Object Oriented Programming in Java

double area = [Link](); // invoking method


double circumf = [Link]();
[Link]("Radius="+aCircle.r+" Area="+area);
[Link]("Radius="+aCircle.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 double circumference( ) {
return 2*3.14*r;
}
public double area( ) {
return 3.14 * r * r;
}

DMU IT Dep’t Page 7


Object Oriented Programming in Java

public static void main (String args[]){


Circle c1=new Circle();
[Link]("The value of x is " + c1.x);
[Link]("The value of yis "+ c1.y);
[Link]("The value of r is " + c1.r);
Circle c2=new Circle(4,2,5);
[Link]("The value of x is " + c2.x);
[Link]("The value of y is " + c2.y);
[Link]("The value of r is " + c2.r);
[Link]("Area of c2 is" +[Link]( ));
[Link]("Circumference of c2 is "+c2. circumference( ));
}
}
Example 3: It contains two constructors - Default and Parameterized. This example is
about a polygon, Cube
public class Cube1 {
int length;
int width;
int height;
public int getVolume() {
return (length *width * height);
}
Cube1( ) {
length = 0;
width = 0;
height = 0;
}
Cube1 (int l, int b, int h) {
length = l;
width = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1( );
cubeObj2 = new Cube1(10, 10, 10);
[Link]("Volume of Cube is : " + [Link]());
[Link]("Volume of Cube is : " + [Link]());
DMU IT Dep’t Page 8
}
Object Oriented Programming in Java }

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.

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

DMU IT Dep’t Page 9

Common questions

Powered by AI

Constructors in Java differ from regular methods in several key ways. Unlike regular methods, constructors have the same name as the class and do not have a return type. Constructors are automatically invoked when an instance of a class is created, ensuring that the object is initialized with default or specified values . This automatic invocation upon object creation is crucial for setting up initial states for objects, facilitating their use immediately after they are instantiated, which is why constructors are considered a special type of method distinct from others used within a class.

Parameterized constructors improve the flexibility and functionality of object creation in Java by allowing the initialization of objects with different states according to specific requirements. Unlike default constructors, which only assign default values, parameterized constructors can accept arguments that customize the attribute values of the object at the time of its creation . This flexibility enables the creation of objects with varied characteristics within the same class framework, enhancing the versatility of the program by supporting diverse use cases.

In Java, it is important for constructors to have the same name as the class because this is how the Java runtime system differentiates them from other methods and understands that these are intended for object initialization. If this condition is not met, the method will not function as a constructor, meaning it will not automatically be called during the instantiation of the object . This would prevent the automatic setup of object attributes and potentially leave objects in an uninitialized or invalid state upon creation.

The similarity between classes and database tables enhances understanding and utilization of object-oriented programming by providing a familiar analogy for those experienced with database systems. Classes, like database tables, define the structure for storing data with fields and the operations that can be performed on it. Each instance of a class can be compared to a row in a table, encapsulating values for the defined fields . This analogy helps in visualizing and organizing data within an object-oriented framework, making it easier to grasp for those accustomed to the relational database approach.

When designing a class in Java, several factors need to be considered to ensure it effectively models a real-world system. Firstly, the class should accurately represent the entities in the problem domain, including appropriate attributes and methods that reflect their real-world counterparts. Secondly, the class should maintain high cohesion, grouping related functionalities together, and low coupling, minimizing dependencies on other classes. The choice of public vs. private fields and methods should be deliberate to control access and protect data integrity . Considering these factors helps in developing a robust, maintainable, and flexible program structure that accurately mimics real-world systems.

The iterative nature of object-oriented design is crucial because it allows designers to continuously refine and adjust the relationships between classes as more information becomes available about the problem domain. This iterative process involves dividing the problem domain into different types of objects/classes, modeling their relationships, and defining their attributes and behaviors . By iteratively revisiting these tasks, designers can better adapt their solutions to reflect real-world complexities, leading to a more accurate and efficient model of the system.

Encapsulation reduces complexity and improves reliability in object-oriented programming by bundling data with the methods that operate on that data. By encapsulating data within a class, programmers can hide the internal state of objects from the outside world, only exposing necessary components through public methods and fields . This increases cohesion by grouping related functionalities together and reduces coupling by limiting the interactions between different parts of the program, thus enhancing reliability and making maintenance easier.

Prototype construction aids in the object-oriented design process by providing a tangible, simplified version of the intended system. It serves as a skeleton model where classes, objects, and interactions between them are initially outlined. This preliminary structure helps designers and stakeholders better understand the requirements and functionality of the system . In complex problem domains, prototyping allows for early detection of design flaws, facilitates user feedback, and incrementally refines the solution, thus improving the overall design process.

Abstraction is a fundamental aspect of object-oriented programming because it allows developers to simplify complex real-world problems by focusing on the most relevant aspects while ignoring non-essential details. By creating abstract models using classes and objects, programmers can represent and solve intricate problems effectively. Abstraction helps in identifying classes and objects from the problem domain, capturing only the necessary attributes and behaviors required for the solution . This approach streamlines the design process, leading to more manageable and comprehensible code structures.

A default constructor might be insufficient in scenarios where complex initialization logic is required, or specific attributes must be set during object creation. In such cases, the default zero or default value provided automatically may not meet the necessary requirements for the object's functionality. Programmers can address these limitations by defining explicit constructors with parameters that allow passing necessary attributes during initialization . Additionally, custom initialization logic can be embedded within these constructors to ensure that all required conditions and constraints are met at the point of object instantiation.

You might also like