Object Oriented Programming
Object Oriented Programming
Object Oriented Programming
// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output:
30
60
31.0
Polymorphism in Java are mainly of 2 types:
Overloading in Java
Overriding in Java
2. Inheritence: Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and methods) of
another class.
Important terminology:
Super Class: The class whose features are inherited is known as superclass(or a base
class or a parent class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class,
extended class, 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.
The keyword used for inheritance is extends.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
3. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is
the mechanism that binds together code and the data it manipulates.Other way to think about
encapsulation is, it is a protective shield that prevents the data from being accessed by the
code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which they
are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
Encapsulation can be achieved by: Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables.
4. Abstraction: Data Abstraction is the property by virtue of which only the essential details are
displayed to the user.The trivial or the non-essentials 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 behaviours 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 car or applying brakes will stop the car but he does not
know about 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 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.
5. 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:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. 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.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
6. Object: It is a basic unit of Object Oriented Programming and represents the real life entities.
A typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
0. State : It is represented by attributes of an object. It also reflects the properties of an
object.
1. Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
2. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog
7. Method: A method is a collection of statements that perform some specific task and return
result to the caller. A method can perform some specific task without returning anything.
Methods allow us to reuse the code without retyping the code. In Java, every method must be
part of some class which is different from languages like C, C++ and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
public: accessible in all class in your application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier) : accessible within same class
and package within which its class is defined.
The return type : The data type of the value returned by the the method or void if does
not return a value.
Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
Exception list : The exceptions you expect by the method can throw, you can specify
these exception(s).
Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.
8. 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.
Recommended Posts:
// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
// derived class
class MountainBike extends Bicycle
{
// driver class
public class Test
{
public static void main(String args[])
{
}
}
Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
In above program, when an object of MountainBike class is created, a copy of the all methods and
fields of the superclass acquire memory in this object. That is why, by using the object of the
subclass we can also access the members of a superclass.
Please note that during inheritance only object of subclass is created, not the superclass. For more,
refer Java Object Creation of Inherited Class.
Illustrative image of the program:
In practice, inheritance and polymorphism are used together in java to achieve fast performance and
readability of code.
Types of Inheritance in Java
Below are the different types of inheritance which is supported by Java.
1. Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In
image below, the class A serves as a base class for the derived class B.
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate the
// concept of single inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
2. Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base class
and as well as the derived class also act as the base class to other class. In below image, the
class A serves as a base class for the derived class B, which in turn serves as a base class for
the derived class C. In Java, a class cannot directly access the grandparent’s members.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Multilevel inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
3. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class.In below image, the class A serves as a base class for the
derived class B,C and D.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
two t = new two();
t.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
4. Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can have more
than one superclass and inherit features from all parent classes. Please note that Java
does not support multiple inheritance with classes. In java, we can achieve multiple inheritance
only through Interfaces. In image below, Class C is derived from interface A and B.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Multiple inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
interface one
{
public void print_geek();
}
interface two
{
public void print_for();
}
// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output:
Geeks
for
Geeks
5. Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the above types of
inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance
is also not possible with classes. In java, we can achieve hybrid inheritance only
through Interfaces.
Important facts about inheritance in Java
Default superclass: Except Object class, which has no superclass, every class has one and
only one direct superclass (single inheritance). In the absence of any other explicit superclass,
every class is implicitly a subclass of Object class.
Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by java.
Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
Private member inheritance: A subclass does not inherit the private members of its parent
class. However, if the superclass has public or protected methods(like getters and setters) for
accessing its private fields, these can also be used by the subclass.
What all can be done in a Subclass?
In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new
members:
The inherited fields can be used directly, just like any other fields.
We can declare new fields in the subclass that are not in the superclass.
The inherited methods can be used directly as they are.
We can write a new instance method in the subclass that has the same signature as the one in
the superclass, thus overriding it (as in example above, toString() method is overridden).
We can write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it.
We can declare new methods in the subclass that are not in the superclass.
We can write a subclass constructor that invokes the constructor of the superclass, either
implicitly or by using the keyword super.
Java and Multiple Inheritance
Multiple Inheritance is a feature of object oriented concept, where a class can inherit
properties of more than one parent class. The problem occurs when there exist methods with
same signature in both the super classes and subclass. On calling the method, the compiler
cannot determine which class method to be called and even on calling which class method
gets the priority.
Why Java doesn’t support Multiple Inheritance?
Consider the below Java code. It shows error.
filter_none
edit
play_arrow
brightness_4
// First Parent class
class Parent1
{
void fun()
{
System.out.println("Parent1");
}
}
interface PI2
{
// Default method
default void show()
{
System.out.println("Default PI2");
}
}
interface GPI
{
// default method
default void show()
{
System.out.println("Default GPI");
}
}
Encapsulation in Java
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates.Other way to think about encapsulation is, it is a
protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other class and
can be accessed only through any member function of own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
Encapsulation can be achieved by: Declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.
filter_none
edit
play_arrow
brightness_4
// Java program to demonstrate encapsulation
public class Encapsulate
{
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;
filter_none
edit
play_arrow
brightness_4
public class TestEncapsulation
{
public static void main (String[] args)
{
Encapsulate obj = new Encapsulate();
Abstraction in Java
Data Abstraction is the property by virtue of which only the essential details are displayed to the
user.The trivial or the non-essentials 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 car or applying brakes will stop the car but he does not know
about 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 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.
Abstract classes and Abstract methods :
1. An abstract class is a class that is declared with abstract keyword.
2. An abstract method is a method that is declared without an implementation.
3. An abstract class may or may not have all abstract methods. Some of them can be concrete
methods
4. A method defined abstract must always be redefined in the subclass,thus
making overriding compulsory OR either make subclass itself abstract.
5. Any class that contains one or more abstract methods must also be declared with abstract
keyword.
6. There can be no object of an abstract class.That is, an abstract class can not be directly
instantiated with the new operator.
7. An abstract class can have parametrized constructors and default constructor is always present
in an abstract class.
When to use abstract classes and abstract methods with an example
There are situations in which we will want to define a superclass that declares the structure of a
given abstraction without providing a complete implementation of every method. That is, sometimes
we will want to create a superclass that only defines a generalization form that will be shared by all
of its subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design system or game
simulation. The base type is “shape” and each shape has a color, size and so on. From this, specific
types of shapes are derived(inherited)-circle, square, triangle and so on – each of which may have
additional characteristics and behaviors. For example, certain shapes can be flipped. Some
behaviors may be different, such as when you want to calculate the area of a shape. The type
hierarchy embodies both the similarities and differences between the shapes.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Abstraction
abstract class Shape
{
String color;
@Override
double area() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public String toString() {
return "Circle color is " + super.color +
"and area is : " + area();
}
}
class Rectangle extends Shape{
double length;
double width;
@Override
public String toString() {
return "Rectangle color is " + super.color +
"and area is : " + area();
}
}
public class Test
{
public static void main(String[] args)
{
Shape s1 = new Circle("Red", 2.2);
Shape s2 = new Rectangle("Yellow", 2, 4);
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}
Output:
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0
Encapsulation vs Data Abstraction
1. Encapsulation is data hiding(information hiding) while Abstraction is detail
hiding(implementation hiding).
2. While encapsulation groups together data and methods that act upon the data, data abstraction
deals with exposing the interface to the user and hiding the details of implementation.
Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.
3. Helps to increase security of an application or program as only important details are provided to
the user.
Related articles :
Interfaces in java
Abstract classes in java
Difference between abstract class and interface
abstract keyword in java
Classes and Objects in Java
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the
real life entities.
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:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. 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.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provides the state of the
class and its objects, and methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.
Object
It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists
of :
1. State : It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an object
with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog
Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as
“shopping cart”, “customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique
for each object. A single class may have any number of instances.
Example :
As we declare variables like (type name;). This notifies the compiler that we will use name to refer to
data whose type is type. With a primitive variable, this declaration also reserves the proper amount
of memory for the variable. So for reference variable, type must be strictly a concrete class name. In
general,we can’t create objects of an abstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an object is
actually created and assigned to it. Simply declaring a reference variable does not create an object.
Initializing an object
The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the class constructor.
filter_none
edit
play_arrow
brightness_4
// Class Declaration
// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
// method 4
public String getColor()
{
return color;
}
@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}
Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java
compiler automatically provides a no-argument constructor, also called the default constructor. This
default constructor calls the class parent’s no-argument constructor (as it contain only one statement
i.e super();), or the Object class constructor if the class has no other parent (as Object class is
parent of all classes either directly or indirectly).
Methods in Java
A method is a collection of statements that perform some specific task and return the result to the
caller. A method can perform some specific task without returning anything. Methods allow us
to reuse the code without retyping the code. In Java, every method must be part of some class
which is different from languages like C, C++, and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
public: accessible in all class in your application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier) : accessible within same class and
package within which its class is defined.
The return type : The data type of the value returned by the method or void if does not return a
value.
Method Name : the rules for field names apply to method names as well, but the convention is
a little different.
Parameter list : Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().
Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).
Method body : it is enclosed between braces. The code you need to be executed to perform
your intended operations.
Method signature: It consists of the method name and a parameter list (number of parameters, type
of the parameters and order of the parameters). The return type and exceptions are not considered
as part of it.
Method Signature of above function:
max(int x, int y)
How to name a Method?: A method name is typically a single word that should be a verbin
lowercase or multi-word, that begins with a verb in lowercase followed by adjective, noun….. After
the first word, first letter of each word should be capitalized. For example, findSum,
computeMax, setX and getX
Generally, A method has a unique name within the class in which it is defined but sometime a
method might have the same name as other method names within the same class as method
overloading is allowed in Java.
Calling a method
The method needs to be called for using its functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:
It completes all the statements in the method
It reaches a return statement
Throws an exception
filter_none
edit
play_arrow
brightness_4
// Program to illustrate methodsin java
import java.io.*;
class Addition {
int sum = 0;
class GFG {
public static void main (String[] args) {
}
}
Output :
Sum of two integer values :3
See the below example to understand method call in detail :
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate different ways of calling a method
import java.io.*;
class Test
{
public static int i = 0;
// constructor of class which counts
//the number of the objects of the class.
Test()
{
i++;
}
// static method is used to access static members of the class
// and for getting total no of objects
// of the same class created so far
public static int get()
{
// statements to be executed....
return i;
}
class GFG
{
public static void main(String[] args)
{
// Creating an instance of the class
Test obj = new Test();
}
}
Output :
Inside the method m1 by object of GFG class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now : 1
Control flow of above program:
// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output:
30
60
31.0
Polymorphism in Java are mainly of 2 types:
Overloading in Java
Overriding in Java
2. Inheritence: Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and methods) of
another class.
Important terminology:
Super Class: The class whose features are inherited is known as superclass(or a base
class or a parent class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class,
extended class, 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.
The keyword used for inheritance is extends.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
3. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is
the mechanism that binds together code and the data it manipulates.Other way to think about
encapsulation is, it is a protective shield that prevents the data from being accessed by the
code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which they
are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
Encapsulation can be achieved by: Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables.
4. Abstraction: Data Abstraction is the property by virtue of which only the essential details are
displayed to the user.The trivial or the non-essentials 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 behaviours 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 car or applying brakes will stop the car but he does not
know about 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 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.
5. 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:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. 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.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
6. Object: It is a basic unit of Object Oriented Programming and represents the real life entities.
A typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
0. State : It is represented by attributes of an object. It also reflects the properties of an
object.
1. Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
2. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog
7. Method: A method is a collection of statements that perform some specific task and return
result to the caller. A method can perform some specific task without returning anything.
Methods allow us to reuse the code without retyping the code. In Java, every method must be
part of some class which is different from languages like C, C++ and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
public: accessible in all class in your application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier) : accessible within same class
and package within which its class is defined.
The return type : The data type of the value returned by the the method or void if does
not return a value.
Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
Exception list : The exceptions you expect by the method can throw, you can specify
these exception(s).
Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.
8. 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.
1) Method overloading is used to increase the readability of the Method overriding is used to provide the
program. specific implementation of the method that i
already provided by its super class.
2) Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.
3) In case of method overloading, parameter must be different. In case of method overriding, parameter mu
be same.
4) Method overloading is the example of compile time Method overriding is the example of run tim
polymorphism. polymorphism.
5) In java, method overloading can't be performed by changing Return type must be same or covariant in
return type of the method only. Return type can be same or method overriding.
different in method overloading. But you must have to change the
parameter.