MODULE I
JAVA PROGRAMMING
MODULE I
OBJECT-ORIENTED PROGRAMMING (OOP)
Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior focuses on the objects that developers want to manipulate rather than the logic required to manipulate them. This approach to programming is well-suited for programs that are large, complex and actively updated or maintained. This includes programs for manufacturing and design, as well as mobile applications; for example, OOP can be used for manufacturing system simulation software. The organization of an object-oriented program also makes the method beneficial to collaborative development, where projects are divided into groups. Additional benefits of OOP include code reusability, scalability and efficiency. Examples of an object can range from physical entities, such as a human being who is described by properties like name and address, to small computer programs, such as widgets.
Once an object is known, it is labeled with a class of objects that defines the kind of data it contains and any logic sequences that can manipulate it. Each distinct logic sequence is known as a method. Objects can communicate with well-defined interfaces called messages.Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
STRUCTURE OF OBJECT-ORIENTED PROGRAMMING
The structure, or building blocks, of object-oriented programming include the following:
Classes are user-defined data types that act as the blueprint for individual objects, attributes and methods.
Objects are instances of a class created with specifically defined data. Objects can correspond to real-world objects or an abstract entity. When class is defined initially, the description is the only object that is defined.
Methods are functions that are defined inside a class that describe the behaviors of an object. Each method contained in class definitions starts with a reference to an instance object. Additionally, the subroutines contained in an object are called instance methods. Programmers use methods for reusability or keeping functionality encapsulated inside one object at a time.
Attributes are defined in the class template and represent the state of an object. Objects will have data stored in the attributes field. Class attributes belong to the class itself.
OOPS concepts are as follows:
• Class
• Object
• Method
• Encapsulation
• Abstraction
• Polymorphism
• Inheritance
• Message Passing
Class
A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: Modifiers: A class can be public or has default access (Refer this for details). Class name: The name should begin with a initial letter (capitalized by convention). Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, proceeded by the keyword implements. A class can implement more than one interface. Body: The class body surrounded by braces, { }.
Object
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It 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.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
Object Definitions:
- An object is a real-world entity.
- An object is a runtime entity.
- The object is an entity which has state and behavior.
- The object is an instance of a class.
Method in Java
-
- In general, a method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task. It provides the reusability of code. We can also easily modify code using methods. In this section, we will learn what is a method in Java, types of methods, method declaration, and how to call a 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.
Method Declaration
- The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments. It has six components that are known as method header, as we have shown in the following figure.
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.
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.
Encapsulation
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.
Advantage of Encapsulation in Java
By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.
ABSTRACTION
Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essential units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of a car or applying brakes will stop the car, but he does not know how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.
INHERITANCE
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of (Object Oriented programming system).The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java
- For Method Overriding
- For Code Reusability.
Terms used in Inheritance
- Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
- Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
- Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
- Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
Definition
}
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.
TYPES OF INHERITANCE IN JAVA
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
POLYMORPHISM
Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
Types of Polymorphism
There are two types of polymorphism in Java:
- Static Polymorphism (Compile Time Polymorphism)
- Dynamic Polymorphism (Run Time Polymorphism)
Dynamic Polymorphism
Dynamic polymorphism is a process or mechanism in which a call to an overridden method is to resolve at runtime rather than compile-time. It is also known as runtime polymorphism or dynamic method dispatch. We can achieve dynamic polymorphism by using the method overriding.
In this process, an overridden method is called through a reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Properties of Dynamic Polymorphism
- It decides which method is to execute at runtime.
- It can be achieved through dynamic binding.
- It happens between different classes.
- It is required where a subclass object is assigned to a super-class object for dynamic polymorphism.
- Inheritance involved in dynamic polymorphism.
Method Overriding
It provides a specific implementation to a method that is already present in the parent class. it is used to achieve run-time polymorphism. Remember that, it is not possible to override the static method. Hence, we cannot override the main() method also because it is a static method.
Rules for Method Overriding
- The name of the method must be the same as the name of the parent class method.
- The number of parameters and the types of parameters must be the same as in the parent class.
- There must exist an IS-A relationship (inheritance).
We call an overridden method through a reference of the parent class. The type of object decides which method is to be executed and it is decided by the JVM at runtime.
DynamicPolymorphismExample.java
public class DynamicPolymorphismExample
{
public static void main(String args[])
{
//assigning a child class object to a parent class reference
Fruits fruits = new Mango();
//invoking the method
fruits.color();
}
}
//parent class
class Fruits
{
public void color()
{
System.out.println("Parent class method is invoked.");
}
}
//derived or child class that extends the parent class
class Mango extends Fruits
{
//overrides the color() method of the parent class
@Override
public void color()
{
System.out.println("The child class method is invoked.");
}
}
Output:
The child class method is invoked.
In the above example, we have used an annotation @Override. It indicates that the child class method is over-writing its base class method.
Example of Dynamic Polymorphism
In the following example, we have created two classes named Sample and Demo. The Sample class is a parent class and the Demo class is a child or derived class. The child class is overriding the dispaly() method of the parent class.
We have assigned the child class object to the parent class reference. So, in order to determine which method would be called, the type of the object would be decided by the JVM at run-time. It is the type of object that determines which version of the method would be called (not the type of reference).
Suppose a subclass overrides a particular method of the superclass. Let’s say we create an object of the bRuntime Polymorphism or Dynamic method dispatch
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to. In simple words the type of object which it referred determines which version of overridden method will be called.
Subclass: The class that inherits the other class is known as subclass (also known as derived or extended or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
Difference between Static binding and Dynamic binding in Java?
• Static binding in Java occurs during compile time while dynamic binding occurs during runtime.
• Static binding uses type (Class) information for binding while dynamic binding uses instance of class (Object) to resolve calling of method at runtime.
• Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
• In simpler terms, Static binding means when the type of object which is invoking the method is determined at compile time by the compiler while Dynamic binding means when the type of object which is invoking the method is determined at run time by the compiler.
MESSAGE PASSING
Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function and the information to be sent
What are benefits of OOP?
• Code reusability new objects can be derived from old objects, allowing for improvement and refinement of the code at each stage and also preserving parts of the code for other programs. This is used to develop many class libraries using class codes that have already been written, for example, Microsoft Foundation Classes (MFC).
• Code Modularity Everything in OOP is an object; these objects can be interchanged or removed to meet the users’ needs.
• Easier maintenance Inheritance usually reduces maintenance because of the ‘domino effect it has on derived classes when a change is made in a base class.
• Design stability once a stable base class has been developed, the new classes that are derived may have fewer less errors and bugs.
• Improved communication between developers and users Objects can be broken down into real life entities; hence it is easier it communicate ideas.
• Seamless transition from design to implementation this is mainly because communications are improved
നിങ്ങൾക്ക് ഉപകാരപ്പെട്ടെങ്കിൽ നിങ്ങളുടെ കൂട്ടുകാർക്ക് കൂടി ഷെയർ ചെയ്യുക
Share This