No announcement
 

Introduction to Object-Oriented Programming

Object-oriented programming (OOP), is a programming paradigm that has replaced the procedural programming technique. In object-oriented programming, a program is made of objects. Each object has its own specific functionality, which is exposed to the user, but its implementation is hidden from the user.

In procedural programming, the focus is on designing a set of procedures to solve a problem. Once the procedures have been identified, the next step is to determine appropriate ways to store the data. Such technique is good for small programs, but while dealing with large program, say, a website, which shares global data, then procedural programming won’t be the right choice it may require a significant amount of procedures, which may make the program more complex. Object-oriented programming simplifies such complex scenarios.

Classes

A class is a blueprint for creating objects (a data structure), providing initial values to the state (member variables or attributes), and implementation of behaviour (member methods or functions).

User defined object are created using the keyword class.

Syntax:

class <ClassName>
{
    Member variables;
    Member methods();
}

Objects

An object has three key characteristics, namely:

  1. State – what the object currently looks like, i.e. its value.
  2. Behaviour – represent the functionality of the object.
  3. Identity – unique id of the object.

Methods

A method is like a function which is used to expose the behaviour of an object. A method is a collection of statements to perform certain task. Every method has a method signature. It is a part of the method declaration and includes the method name and parameters.

Syntax:

<Access Specifier> <Return Type> <Method Name> (<Parameters>)
{
    // Statements;
}

Access Specifier: This specifies the visibility of the method. There are four types of access modifiers:

  1. Public: The method is accessible by all classes.
  2. Private: The method is accessible only in the classes in which it is defined.
  3. Protected: The method is accessible within the same package or subclasses in a different package.
  4. Default: If we do not specify any access modifier then Java uses default access specifier by default. It is visible only from the same package only.

Return Type: Return type defines the type of value returned by the method. It may be primitive data type, object, collection, void, etc. If the method does not return anything, we have to specify void keyword.

Method Name: It is a unique name of the method and must correspond to the functionality of the method.

Parameters: It is a 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, leave the parentheses empty.

An example of method is the main method.