[Go to site: main page, start]

0% found this document useful (0 votes)
31 views8 pages

Java OOP Concepts and Examples

Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. The document discusses the key concepts of OOP in Java including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It provides examples to illustrate class creation, object instantiation, method overriding, abstract classes, interfaces, and encapsulation in Java.

Uploaded by

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

Java OOP Concepts and Examples

Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. The document discusses the key concepts of OOP in Java including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It provides examples to illustrate class creation, object instantiation, method overriding, abstract classes, interfaces, and encapsulation in Java.

Uploaded by

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

JAVA

Object Oriented Programming


Java
Object Oriented Programming
Object means a real-world entity such as a pen, chair, table, computer, watch, etc.

Object-Oriented Programming is a methodology or paradigm to design


a program using classes and objects. It simplifies software
development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Object
Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Example:
class Student {
String name;
int age;
public void getInfo() {
[Link]("The name of this Student is " + [Link]);
[Link]("The age of this Student is " + [Link]);
}
}
public class OOPS {
public static void main(String args[]) {
Student s1 = new Student();
[Link] = "Aman";
[Link] = 24;
[Link]();
Student s2 = new Student();

Raj Singh, Access more from my GitHub


Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance, the information is made manageable in a hierarchical
order.
The class which inherits the properties of other is known as subclass (derived class, child class) and
the class whose properties are inherited is known as superclass (base class, parent class).

extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends
keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

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.

Types of Inheritance explained:


1. Single inheritance: When one class inherits another class, it is known as single level inheritance
class Shape {
public void area() {
[Link]("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
}
}

Raj Singh, Access more from my GitHub


2. Hierarchical inheritance: Hierarchical inheritance is defined as the process of deriving more
than one class from a base class.
class Shape {
public void area() {
[Link]("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
}
}
class Circle extends Shape {
public void area(int r) {
[Link]((3.14)*r*r);
}
}
3. Multilevel inheritance: Multilevel inheritance is a process of deriving a class from another
derived class.
class Shape {
public void area() {
[Link]("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
}
}
class EquilateralTriangle extends Triangle {
int side;
}
4. Hybrid inheritance: Hybrid inheritance is a combination of simple, multiple inheritance and
hierarchical inheritance.
Polymorphism
Polymorphism is the ability to present the same interface for differing underlying forms (data types).
With polymorphism, each of these classes will have different underlying data. Precisely, Poly means
‘many’ and morphism means ‘forms’.

Types of Polymorphism IMP


1. Compile Time Polymorphism (Static)
2. Runtime Polymorphism (Dynamic)

Compile Time Polymorphism: The polymorphism which is implemented at the compile time is
known as compile-time polymorphism. Example - Method Overloading

Method Overloading: Method overloading is a technique which allows you to have more
than one function with the same function name but with different functionality. Method overloading
can be possible on the following basis:
1. The return type of the overloaded function.
2. The type of the parameters passed to the function.
3. The number of parameters passed to the function.

Raj Singh, Access more from my GitHub


Code:
class Student {
String name;
int age;

public void displayInfo(String name) {


[Link](name);
}

public void displayInfo(int age) {


[Link](age);
}

public void displayInfo(String name, int age) {


[Link](name);
[Link](age);
}
}
Runtime Polymorphism: Runtime polymorphism is also known as dynamic polymorphism.
Function Overriding is an example of runtime polymorphism.
Function Overriding means when the child class contains the method which is already
present in the parent class. Hence, the child class overrides the method of the parent class. In
case of function overriding, parent and child classes both contain the same function with a different
definition. The call to the function is determined at runtime is known as runtime polymorphism.
Code:
class Shape {
public void area() {
[Link]("Displays Area of Shape");
}
}
class Triangle extends Shape {
public void area(int h, int b) {
[Link]((1/2)*b*h);
}
}
class Circle extends Shape {
public void area(int r) {
[Link]((3.14)*r*r);
}
}

Abstraction
Abstraction is a process of hiding the implementation details from the user, only the functionality
will be provided to the user.
In other words, the user will have the information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.
Abstraction is achieved in 2 ways:
• Abstract class
• Interfaces (Pure Abstraction)
Abstract Class
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the method.

Raj Singh, Access more from my GitHub


Code:
abstract class Animal {
abstract void walk();
void breathe() {
[Link]("This animal breathes air");
}
Animal() {
[Link]("You are about to create an Animal.");
}
}

class Horse extends Animal {


Horse() {
[Link]("Wow, you have created a Horse!");
}
void walk() {
[Link]("Horse walks on 4 legs");
}
}

class Chicken extends Animal {


Chicken() {
[Link]("Wow, you have created a Chicken!");
}
void walk() {
[Link]("Chicken walks on 2 legs");
}
}

public class OOPS {


public static void main(String args[]) {
Horse horse = new Horse();
[Link]();
[Link]();
}
}
Interfaces
• All the fields in interfaces are public, static and final by default.
• All methods are public & abstract by default.
• A class that implements an interface must implement all the methods declared in the
interface.
• Interfaces support the functionality of multiple inheritance.

Code:
interface Animal {
void walk();
}
class Horse implements Animal {
public void walk() {
[Link]("Horse walks on 4 legs");
}
}
class Chicken implements Animal {
public void walk() {
[Link]("Chicken walks on 2 legs");
}
}
public class OOPS {
public static void main(String args[]) {
Horse horse = new Horse();
[Link]();
}
}

Raj Singh, Access more from my GitHub


Encapsulation
Encapsulation is the process of combining data and functions into a single unit called class.
In Encapsulation, the data is not accessed directly; it is accessed through the functions present inside
the class. In simpler words, attributes of the class are kept private or public - getter and setter
methods are provided to manipulate these attributes. Thus, encapsulation makes the concept of
data hiding possible. (Data hiding: a language feature to restrict access to members of an object,
reducing the negative effect due to dependencies. e.g., "protected", "private" feature in Java).
To achieve encapsulation in Java −
o Declare the variables of a class as private.
o Provide public setter and getter methods to modify and view the variables values.

Code:
/* File name: [Link] */
public class EncapTest {
private String name;
private String idNum;
private int age;

public int getAge() {


return age;
}

public String getName() {


return name;
}

public String getIdNum() {


return idNum;
}

public void setAge( int newAge) {


age = newAge;
}

public void setName(String newName) {


name = newName;
}

public void setIdNum( String newId) {


idNum = newId;
}
}
/* The public setXXX() and getXXX() methods are the access points of the instance variables of
the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any
class that wants to access the variables should access them through these getters and setters. */
/* The variables of the EncapTest class can be accessed using the following program */

/* File name: [Link] */


public class RunEncap {

public static void main(String args[]) {


EncapTest encap = new EncapTest();
[Link]("James");
[Link](20);
[Link]("12343ms");

[Link]("Name: " + [Link]() + " Age: " + [Link]());


}
}

Raj Singh, Access more from my GitHub


Benefits of Encapsulation
o The fields of a class can be made read-only or write-only.
o A class can have total control over what is stored in its fields.
Advantages of Encapsulation:
• Data Hiding: The user will have no idea about the inner implementation of the class. It will
not be visible to the user that how the class is storing values in the variables. He only knows
that we are passing the values to a setter method and variables are getting initialized with
that value.
• Increased Flexibility: We can make the variables of the class as read-only or write-only
depending on our requirement. If we wish to make the variables as read-only then we have
to omit the setter methods like setName(), setAge() etc. from the above program or if we
wish to make the variables as write-only then we have to omit the get methods like
getName(), getAge() etc. from the above program
• Reusability: Encapsulation also improves the re-usability and easy to change with new
requirements.
• Testing code is easy: Encapsulated code is easy to test for unit testing.

References,
• JavaTpoint
• GeeksForGeeks
• TutorialsPoint
• Oracle Java Documentations
• And Self Explored

Must Visit,
• Explore More from my GitHub

Raj Singh, Access more from my GitHub

Common questions

Powered by AI

Inheritance allows a new class (subclass) to inherit properties and behaviors from an existing class (superclass), promoting code reusability by allowing existing code to be utilized in new contexts without alterations. This hierarchical structuring manages information effectively . Polymorphism, through compile-time polymorphism (e.g., method overloading) and runtime polymorphism (e.g., method overriding), enables objects to be treated as instances of their parent class, allowing flexibility in invoking methods. This means a single function can act differently based on the object’s actual class, thus adapting general methods for specific needs without modifying the underlying code .

Abstract classes provide a way to define both shared behavior and state, offering a more uniform base for subclasses when common implementation is necessary. They allow constructors and fields, which interfaces lack, thus providing a more robust modeling tool when full abstraction is not required. However, they lack the multiple inheritance features of interfaces, limiting flexibility in design. Using abstract classes can also lead to a tighter coupling between a superclass and its subclasses, making future changes riskier unless carefully managed. With the introduction of default methods in interfaces, the gap between interfaces and abstract classes has lessened, allowing more flexible design choices .

Hierarchical inheritance in Java allows multiple subclasses to inherit from a single superclass, promoting a clear organizational structure and reuse of shared code across derived classes. This setup enhances maintainability by localizing shared functionality in a base class, reducing code duplication. However, if not managed properly, the complexity can increase due to the higher number of classes and dependencies, potentially affecting readability. Good design and thorough documentation are crucial to leveraging hierarchical inheritance effectively .

Method overloading is a form of static polymorphism where multiple methods have the same name but differ in parameters, such as type or number of arguments. This is resolved at compile time, enabling multiple forms of a method within a single class to handle different data inputs without changing the method name. This improves code readability by using intuitive names, while maintaining efficiency since the method that matches the invocation parameters is called directly without runtime checks .

The 'extends' keyword in Java is used for inheritance, where a subclass gains access to the fields and methods of its superclass. This promotes code reuse and hierarchical classification of classes, enabling developers to build flexible systems with shared properties. Designing with 'extends' ensures that modifications to a superclass can automatically benefit all its subclasses, enhancing maintainability but requires careful planning to avoid tight coupling .

Abstract classes in Java can have both abstract and concrete methods, allowing common behaviors to be shared among subclasses while requiring implementation of specific methods. They can also include fields, constructors, and methods with operational logic, which interfaces cannot. Interfaces, on the other hand, define a contract with only abstract methods (although they can contain default methods and static methods in newer Java versions) and constant fields, supporting a form of pure abstraction. Interfaces offer a more flexible way to achieve polymorphism and support multiple inheritance, whereas an abstract class is more suited for situations where there is a common base with shared behavior .

Method overriding in Java occurs when a subclass provides a specific implementation for a method already defined in its superclass. This is a form of runtime polymorphism where the actual method to be invoked is determined at runtime, known as dynamic method dispatch. It allows a subclass object to invoke its specific method when called through a reference of a superclass type, enabling developers to design flexible systems that respond dynamically based on object types .

Constructors in an abstract class initialize fields of the class and set up initial states required by subclasses. Although abstract classes cannot be instantiated directly, their constructors are called when an instance of a concrete subclass is created, ensuring the superclass part of the object is properly initialized. This allows for the establishment of required setup, such as default settings or mandatory resources, across subclasses that extend the abstract class .

Encapsulation in Java is the process of combining data and functions into a single unit called a class. It supports data hiding by restricting access to the class's internal data, exposing only necessary aspects through public methods. By making class variables private and providing public getter and setter methods, encapsulation controls access and modification of variables, ensuring controlled interaction. This minimizes negative dependencies, enhancing security and integrity of data .

Encapsulation in Java aids the object-oriented principle of data protection by restricting access to an object's internal data, requiring outsiders to interact with it via well-defined interfaces. This modular approach isolates internal changes within classes, reducing the risk of unintended interference and errors from external classes. It also enforces a clean separation between an object's interface and its implementation, enhancing reusability and flexibility in updating or scaling individual modules without affecting the broader system .

You might also like