OOPS With CJava Programming
OOPS With CJava Programming
1|Page
Introduction
What is OOPs?
Object
Class
Abstraction
Inheritance
Polymorphism
Encapsulation
2|Page
What are Objects?
Objects are always called as instances of a class. Objects are created from class in
java or any other languages. Objects are those that have state and behaviour.
Objects are abstract data types (i.e., objects behaviour is defined by a set of values
and operations).
These objects always correspond to things found in the real world, i.e., real entities.
So, they are also called a run time entity of the world. These are self–contained
which consists of methods and properties which makes data useful. Objects can be
both physical and logical data. It contains addresses and takes up some space in
memory. Some of the examples of objects are a dog, chair, tree etc.
When we treat animals as objects, it has states like colour, name, breed etc., and
behaviors such as eating, wagging the tail etc.
Suppose, we have created a class called My book, we specify the class name followed
by the object name, and we use the keyword new.
Example 1:
3|Page
This is the statement used for creating objects.
[Link](Myobj.x);
We can also create multiple objects in the same class and we can create in one class
and access it in another class. This method is used for better organization of classes
and always remembers that name of the java file and the class name remains the
same.
Example 2:
The below example shows how multiple objects are created in the same class and
how they are accessed from another class.
[Link]
[Link]
1 Class Count {
2 Public static void main (String [] args)
3 {
4 Mybook myobj1 = new myobj1();
5 Mybook myobj2 = new myobj2();
6 [Link] (myobj1.x);
7 [Link] (myobj2.y);
8 }
9 }
When this program is compiled, it gives the result as 10, 8 respectively.
4|Page
What are Classes?
Classes are like an object constructor for creating objects. Collection of objects is said
to be a class. Classes are said to be logical quantities. Classes don’t consume any
space in the memory. Class is also called a template of an object. Classes have
members which can be fields, methods and constructors. A class has both static and
instance initializers.
Modifiers
Class name
Keywords
The class body within { } brackets.
A class keyword is used to create a class. A simplified general form of class definition
is given below:
1 class classname {
2 type instance variable 1;
3 type instance variable 2;
4 .
5 .
6 .
7 type instance variable n;
8 type methodname 1 (parameter list) {
9 // body od method
10 }
11 type methodname 2 (parameter list) {
12 // body od method
13 }
14 type methodnamen (parameter list) {
15 // body od method
16 }
17 }
5|Page
The variables or data defined within a class are called as instance variables. Code is
always contained in the methods. Therefore, the methods and variables defined
within a class are called members of the class. All the methods have the same form
as main () these methods are not specified as static or public.
What is Abstraction?
Abstraction is a process which displays only the information needed and hides the
unnecessary information. We can say that the main purpose of abstraction is data
hiding. Abstraction means selecting data from a large number of data to show the
information needed, which helps in reducing programming complexity and efforts.
There are also abstract class and abstract methods. An abstract class is a type of class
that declares one or more abstract methods. An abstract method is a method that
has a method definition but not implementation. Once we have modelled our object
using data abstraction, the same sets of data can also be used in different
applications—abstract classes, generic types of behaviours and object-oriented
programming hierarchy. Abstract methods are used when two or more subclasses do
the same task in different ways and through different implementations. An abstract
class can have both the methods, i.e., abstract methods and regular methods.
Suppose we want to create a student application and ask to collect the information
about the student.
Name
Class
6|Page
Address
Dob
Fathers name
Mothers name and so on.
We may not require every information that we have collected to fill the application.
So, we select the data that is required to fill the application. Hence, we have fetched,
removed, and selected the data, the student information from large data. This
process is known as abstraction in oops concept.
What is Inheritance?
7|Page
from an existing class, we can reuse methods and fields of the parent class.
Inheritance represents the parent-child relationship.
For example, a whale is a part of the classification of marine animals, which is part of
class mammal, which is under that class of animal. We use hierarchical classification,
i.e., top-down classification. If we want to describe a more specific class of animals
such as mammals, they would have more specific attributes such as teeth; cold-
blooded, warm-blooded, etc. This comes under the subclass of animals where
animals come under superclass. The subclass is a class which inherits properties of
the superclass. This is also called a derived class. A superclass is a base class or
parental class from which subclass inherits properties.
There are five types of inheritance single, multilevel, multiple, hybrid and
hierarchical.
Single level
In this one class i.e., derived class inherits properties from its parental class. This
enables code reusability and also adds new features to the code. Example: class b
inherits properties from class a.
8|Page
Syntax:
1 Class a {
2 …
3 }
4 Class b extends class a {
5 …
6 }
Multilevel
This one class is derived from another class which is also derived from another class
i.e., this class has more than one parental class, hence it is called multilevel
inheritance.
Syntax:
1 Class a {
2 ….
3 }
4 Class b extends class a {
5 ….
6 }
7 Class c extends class b {
8 …
9 }
Hierarchical level
In this one parental class has two or more derived classes or we can say that two or
more child classes has one parental class.
Syntax:
1 Class a {
2 …
3 }
9|Page
4 Class b extends class a {
5 ..
6 }
7 Class c extends class a {
8 ..
9 }
Hybrid inheritance
This is the combination of multiple and multilevel inheritance and in java multiple
inheritance is not supported as it leads to ambiguity and this type of inheritance can
only be achieved through interfaces.
Consider that class a is the parental or base class of class b and class c and in turn
class b and class c are parental or base class of class d. Class b and class c are derived
classes from class a and class d is derived class from class b and class c.
Following program creates a super class called add and a subclass called sub, uses
extend keyword to create a subclass add.
10 | P a g e
18 subOb. Sum ( ) ;
19 [Link](“total =” + subOb. Total);
20 }
21 }
It gives output as – total = 22
What is Polymorphism?
Example:
2 …
5 }
6 }
11 | P a g e
7 public class pigeon extends Bird {
8 …
9 @override
11 [Link]( “ cooing ” ) ;
12 }
13 }
15 ….
16 @override
18 [Link]( “ chip ” ) ;
19 }
20 }
In the above example, we can see common action sound () but there are different
ways to do the same action. This is one of the examples which shows polymorphism.
What is Encapsulation?
Encapsulation is one of the concepts in OOPs concepts; it is the process that binds
together the data and code into a single unit and keeps both from being safe from
outside interference and misuse. In this process, the data is hidden from other
classes and can be accessed only through the current class’s methods. Hence, it is
also known as data hiding. Encapsulation acts as a protective wrapper that prevents
12 | P a g e
the code and data from being accessed by outsiders. These are controlled through a
well-defined interface.
Example:
1 class animal {
2 // private field
4 //getter method
6 return age;
7 }
8 //setter method
11 }
12 }
13 class Main {
13 | P a g e
16 Animal a1= new Animal ();
21 }
22 }
In this example, we declared a private field called age that cannot be accessed
outside of the class.
To access age, we used public methods. These methods are called getter and setter
methods. Making age private allows us to restrict unauthorized access from outside
the class. Hence this is called data hiding.
14 | P a g e
Advantages of OOPs Concept
OOPs concepts are one of the core development approaches which is widely
accepted. Some of the advantages are:
Re-usability
When we say re-usability, it means that “write once, use it multiple times” i.e.,
reusing some facilities rather than building it again and again, which can be achieved
by using class. We can use it n number of times whenever required.
Data redundancy
It is one of the greatest advantages in oops. This is the condition which is created at
the data storage when the same piece of data is held at two different places. If we
want to use a similar functionality in multiple classes, we can just write common
class definitions for the similar functionalities by inheriting them.
Code maintenance
It is easy to modify or maintain existing code as new objects which can be created
with small differences for the existing ones. It also helps users from doing rework
many times. It is time saving as we modify the existing codes incorporating new
changes to it.
Security
Data hiding and abstraction are used to filter out limited exposure which means we
are providing only necessary data to view as we maintain security.
Design benefits
15 | P a g e
The designers will have a longer and extensive design phase, which results in better
designs. At a point of time when the program has reached critical limits, it will be
easier to program all non oops one separately.
Easy troubleshooting
Using encapsulation objects are self-constrained. So, if developers face any problem
easily it can be solved. And there will be no possibility of code duplicity.
Flexibility
Problem solving
16 | P a g e
Coupling in Java
Coupling refers to the relationship between two classes. It indicates the knowledge
one object or class has of another. That means that if one class changes its
properties or behavior, it will affect the dependent changes in the other class.
Therefore, these changes will depend upon the level of interdependence the two
classes have between them. There are two types of coupling, namely tight coupling,
and loose coupling.
17 | P a g e
public class College{
[Link]();
}
In the above code example, the student class is dependent on the college class. That
is, any change in the college class requires student class to change. Here, therefore,
student class and college class are tightly coupled with each other.
void status();
[Link]();
}
In the above code example, CollegeStatus1 and CollegeStatus2 are loosely coupled.
Here, student class is not directly or tightly coupled with a CollegeStatus1 or
CollegeStatus2 class. By applying a dependency injection mechanism, the loose
coupling implementation is achieved to allow a student to go to college with any
class which has implemented a college interface. In addition, it means we can use
CollegeStatus2 whenever the college is open on Saturday.
19 | P a g e
Cohesion in Java
Cohesion measures how the methods and the attributes of a class are meaningfully
and strongly related to each other and how focused they are in performing a single
well-defined task for the system. Cohesion is used to indicate the degree to which a
class has a single, well-focused responsibility. More cohesive classes are good to
keep them for code reusability. Low cohesive classes are difficult to maintain as they
have a less logical relationship between their methods and properties. It is always
better to have highly cohesive classes to keep them well focused for a single work.
Low Cohesion: In the following code, we have a class called Book. But it is
less cohesive because it comprises less focussed and independent
attributes and methods to the class. This class should contain information
related to the Book. Therefore, the person name and age method are
making this classless cohesive.
class Book{
return name;
return subject;
}
20 | P a g e
public int id(int number) {
return number;
return age;
High Cohesion: When the class has a single well-defined purpose or task, it
is said to be highly cohesive. So, in the above example code, if we remove
the information related to the person, then the class becomes highly
cohesive, as shown below.
class Book{
return name;
return subject;
21 | P a g e
public int id(int number) {
return number;
Association in Java
Association is a relation between two separate classes that establishes with the help
of their Objects. It specifies the relationship between two or more Objects.
Association can be one-to-one, one-to-many, many-to-one, many-to-many. Let us
understand this with real-world examples, suppose the relationship between the bus
and the passengers. A bus can have only one driver(one-to-one). Many passengers
can associate with the single bus(many-to-one). A single passenger can associate
with many different buses(one-to-many). Also, many passengers can associate with
the many different buses(many-to-many). One object is associated with another
object to use the functionality and services provided by another object.
//class bus
class Bus
// bus name
Bus(String name)
22 | P a g e
{
[Link] = name;
return [Link];
//passenger class
class Passenger
// passenger name
[Link] = name;
23 | P a g e
[Link] = seatId;
return [Link];
return [Link];
class Demo
24 | P a g e
Passenger psg = new Passenger("Sneha", 52);
}
Output:
Explanation:
In the above example, two separate classes Bus and Passenger, are associated
through their Objects inside the class Demo. In this way, we can establish the
relationship between two different classes by using the concept of association. A bus
can have many passengers, So it is a one-to-many relationship.
Aggregation
25 | P a g e
Person object will not destroy. Aggregation represents the Has-A relationship.
Aggregation is a unidirectional association, i.e., a one-way relationship. For instance,
the group can have persons, but vice versa is not possible and thus unidirectional. In
Aggregation, both the entries can survive individually, which means ending one
entity will not affect the other entity. Hence, both objects are independent in
aggregation.
import [Link].*;
//person class
class Person
[Link] = name;
[Link] = age;
return name;
26 | P a g e
}
return age;
//group class
class Group
[Link] = groupName;
[Link] = persons;
27 | P a g e
}
//main method
class Demo
[Link](a);
[Link](c);
28 | P a g e
[Link](b);
[Link](d);
for(Person p : p2) {
dfGrp = null;
for(Person p : p2) {
29 | P a g e
}
Output:
Explanation:
Here, we can see that the two classes Person and Group, are associated with each
other with the help of objects. There are two groups social welfare and drama fest.
We created these groups by using the person class. The group has a list of persons.
We have two persons Sam and Khushi, in the Drama Fest group as shown in the
output. Afterward, we deleted this group by setting the instance of group equals to
null. But, our list of persons remains undestroyed due to the weak association, i.e.,
aggregation, even after the group was deleted.
30 | P a g e
Composition in Java
Whenever there is a composition between two entities, the created object cannot
exist without the other object. Thus, in composition, both entities are dependent on
each other.
import [Link].*;
class ActivityRoom {
31 | P a g e
[Link] = subject;
[Link] = id;
// department class
class Department {
Department(List<ActivityRoom> ar)
[Link] = ar;
return ar;
32 | P a g e
}
class Demo {
[Link](a1);
[Link](a2);
[Link](a3);
33 | P a g e
// making the list of activity rooms in department.
}
Output:
Explanation:
Here we have two classes Activity room and Department. A department composed of
different subject activity rooms. So, If the department gets destroyed, then All
activity rooms within that department will be destroyed, i.e., the activity room
cannot exist without the department. That’s why it is composition.
34 | P a g e
Methods in Java
Let’s discuss:
A method that has the static keyword in the declaration is known as the static
method. In other words, a method that belongs to a class rather than an instance of
a class is known as a static method. We can also create a static method by using the
keyword static before the method name. The main benefit of a static method is that
we can invoke the static method without even creating an object. It can access static
data members and also change their values. It is used to create an instance method.
It is invoked by using the class name. The main() method is a common example of the
static method.
Example:
35 | P a g e
public class Demo
displaymethod();
}
Output:
A method that is declared with keyword abstract is called an abstract method. The
abstract method does not have an implementation or body, or block of code. The
abstract method must always be declared in an abstract class, or we can say that if a
class has an abstract method, it should be declared abstract. If a class has an abstract
method, it should be declared abstract, but vice versa is not true, which means that
an abstract class doesn’t need to have an abstract method compulsory. Also, If a
normal class extends an abstract class, then the class must have to implement all the
abstract parent class’s abstract methods, or it has to be declared abstract.
36 | P a g e
Example:
*/
//Normal method
*/
37 | P a g e
public int areaSquare(int s){
return s*s;
return l*b;
[Link]();
}
Output:
Area of square 81
Area of rectangle 12
38 | P a g e
Final Method in Java
A method that is declared final is called a final method. We cannot override a final
method. This means the child class can still call the final method of parent class
without any problem, but it cannot override it. This is because the main purpose of
making a method final is to stop the modification of the method by the sub-class.
Example:
class DemoParent{
//error
void method(){
[Link]();
39 | P a g e
}
}
The above code will throw an error as we are trying to modify the final method
inside the child class(demo) of the parent class(demoParent).
class DemoParent{
[Link]();
}
Output:
40 | P a g e
Equals Method in Java
As the name suggests in java, .equals() is a method used to compare two objects for
equality. The .equals() method in java is used to check if the two strings have similar
values. It checks them character by character. One should not confuse .equals()
method with == operator. The String equals() method compares the two given strings
based on the content of the string, whereas the == operator is used for address
comparison. If all the contents of both the strings are the same, then .equals()
returns true otherwise, it returns false. If all characters are not matched, then it
returns false.
String s1 = "GreatLearning";
String s2 = "GreatLearning";
[Link]([Link](s2)); // true
[Link]([Link](s3)); // true
41 | P a g e
}
Even though s1 and s3 are created with the same field(content), they are pointing to
two different objects in memory. Hence at different addresses. Therefore ==
operator gives false and .equals() method gives true as both contain similar content
great Learning.
Synchronous message passing occurs when the objects run at the same
time.
In the case of an Asynchronous message passing, the receiving object
42 | P a g e
Differences between Object-Oriented Programming, Procedural
Oriented Programming, Structured Programming?
Object-oriented programming
It is object oriented.
It follows a bottom-up approach.
These are divided into small parts called objects.
These have specifiers like public, private, protected.
Adding new functions or data is easy.
It provides data hiding and it is more secure.
Overloading is possible.
Examples are c++, java, python etc.
It is structured oriented.
It is divided into small parts called functions.
It follows a top-down approach.
There are no access specifiers.
Adding new data and functions is not easy.
This is less secure.
Overloading is not possible.
Examples FORTRAN, Cobol etc.
Structured programming
This divides a program into functions and modules, using this function and
modules it makes the program more understandable and readable. It gives
importance to functions rather than data and focuses on development on
large software applications.
Example c, pascal.
43 | P a g e