[go: up one dir, main page]

0% found this document useful (0 votes)
10 views18 pages

introduction to object oriented programing-java-4th-sem

Object-Oriented Design (OOD) is a programming paradigm that structures software systems as collections of objects representing real-world entities, utilizing principles such as encapsulation, inheritance, and polymorphism. Java, as an object-oriented language, employs classes and objects, constructors, and access modifiers to facilitate modularity, reusability, and maintainability in code. Additionally, concepts like method overloading, abstract classes, and interfaces further enhance the flexibility and organization of Java programs.

Uploaded by

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

introduction to object oriented programing-java-4th-sem

Object-Oriented Design (OOD) is a programming paradigm that structures software systems as collections of objects representing real-world entities, utilizing principles such as encapsulation, inheritance, and polymorphism. Java, as an object-oriented language, employs classes and objects, constructors, and access modifiers to facilitate modularity, reusability, and maintainability in code. Additionally, concepts like method overloading, abstract classes, and interfaces further enhance the flexibility and organization of Java programs.

Uploaded by

kamran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

introduction to object oriented design

Object-Oriented Design (OOD) is a programming approach that uses the principles


of Object-Oriented Programming (OOP) to design software systems. This
approach structures programs by modeling them as a collection of objects that
represent real-world entities and their interactions. Here’s a brief breakdown of
the core concepts and principles in OOD:
1. Key Concepts
 Objects: An object is an instance of a class that contains data and methods
to operate on that data.
 For example, in a library system, a book could be represented as an object
with attributes like title, author, and ISBN.

 Classes: A class serves as a blueprint for creating objects. It defines the
attributes and behaviors that the objects created from it will have.
 For instance, a Book class could define attributes such as title, author, and
year.

 Encapsulation: This principle bundles the data (attributes) and methods
(functions or behaviors) that operate on the data into a single unit or class..

 Abstraction: Abstraction means exposing only the necessary details to the
user, hiding complex implementation details.
 It helps reduce complexity by simplifying the view of the object and
focusing on essential characteristics .

 Inheritance: Inheritance allows classes to inherit attributes and behaviors
from other classes, enabling code reuse.
 For example, a LibraryBook class might inherit from a Book class, gaining its
properties and behaviors while adding or modifying as needed.

 Polymorphism: Polymorphism allows methods to perform different tasks
based on the object that invokes them.
 It enables objects of different classes to be treated as objects of a common
superclass.

For instance, in an e-commerce system, Customer, Order, and Product can be
represented directly as classes, mirroring their roles in the business domain.
Java Classes/Objects
Java is an object-oriented programming language.Everything in Java is associated
with classes and objects, along with its attributes and methods. For example: in
real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Create a Class To create a class, use the keyword class:
Example Create an object called "myObj" and print the value of x:

public class Main {


int x = 5;
}
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);}






 Benefits of Object-Oriented Programming

1. Modularity: OOP enables you to break down complex programs into
manageable pieces. Each class serves as a self-contained module that can
be developed, tested, and debugged independently.
2.
3. Reusability: With OOP, you can reuse existing classes in new programs,
minimizing redundancy.
4. For example, if you have a User class in one project, you can use it in
another project with little or no modification.
5.
6. Scalability: OOP is flexible and scalable, making it easier to add new
features or change existing ones without disrupting the entire codebase.
7.
8. Maintainability: Since OOP encourages code modularity and clear
organization, it’s easier to maintain and modify software over time.
9. Encapsulation and abstraction also help to ensure that changes in one part
of a program don’t cause unexpected issues elsewhere.
10.
Real-World Modeling: OOP is intuitive because it models real-world objects
and relationships, making it easier to translate requirements into code.

Java Constructors
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set
initial values for object attributes:
Note that the constructor name must match the class name, and it cannot have
a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
Example
public class Main {
int x;
}
public Main(int y) {
x = y;
}
===================================================
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}

// Outputs 5
Java Destructor
The destructor is the opposite of the constructor. The constructor is used to
initialize objects while the destructor is used to delete or destroy the object that
releases the resource occupied by the object.
What is the destructor in Java?
It is a special method that automatically gets called when an object is no longer
used. When an object completes its life-cycle the garbage collector deletes that
object and deallocates or releases the memory occupied by the object.
It is also known as finalizers that are non-deterministic. In Java, the allocation and
deallocation of objects handled by the garbage collector. The invocation of
finalizers is not guaranteed because it invokes implicitly.
The Java Object class provides the finalize() method that works the same as the
destructor. The syntax of the finalize() method is as follows:
Syntax:
1. protected void finalize throws Throwable()
2. {
3. //resources to be close
4. }

Access Modifiers
For classes, you can use either public or default:
Public The class is accessible by any other class

defaul The class is only accessible by classes in the same package. This is used when you
t don't specify a modifier.

For attributes, methods and constructors, you can use the one of the following:

Public The code is accessible for all classes Try


it »

private The code is only accessible within the declared class Try
it »

default The code is only accessible in the same package. This is used when you Try
don't specify a modifier. You will learn more about packages in it »
the Packages chapter

protected The code is accessible in the same package and subclasses. You will learn
more about subclasses and superclasses in the Inheritance chapter

For attributes and methods, you can use the one of the following:
Final Attributes and methods cannot be overridden/modified

Static Attributes and methods belongs to the class, rather than an object

abstract Can only be used in an abstract class, and can only be used on methods. The
method does not have a body, for example abstract void run();. The body is
provided by the subclass (inherited from).

Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden


from users. To achieve this, you must:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of
a private variable

Get and Set

You learned from the previous chapter that private variables can only be accessed
within the same class (an outside class has no access to it). However, it is possible
to access them if we provide public get and set methods.

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to


the name variable. The this keyword is used to refer to the current object.

Example
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}
===================================================================
==============
}
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}

// Outputs "John"
Java static Keyword
The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static
keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

Example
A static method can be accessed without creating an object of the class first:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
==================================================
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
===================================================
// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error

Main myObj = new Main(); // Create an object of Main


myObj.myPublicMethod(); // Call the public method
}
}

const vs non const function


In object-oriented programming (OOP), the main difference between a const
function and a non-const function is that a const function is read-only and doesn't
modify the object it's called for:
 const function: A const member function is read-only, meaning it can't modify
any non-static data members or call any non-constant member functions.
 Non-const function: A non-const function can modify the object it's called for.
What is a const function in Java?
Constant in Java is an entity that cannot be changed once assigned. Constant
in Java makes the primitive data types immutable.
Syntax: static final datatype identifier_name = value;
The constants are used in Java to make the program easy to understand and
readable.
NOTE: The const keyword is not implemented in Java because Java's final keyword
does a better job of expressing what it means to be a constant in an object-
oriented system. In Java, final is used to perform the following tasks: Mark a
primitive value as being constant. Indicate a method cannot be overridden.

Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which has two methods that add numbers of
different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
}
===================================================
static double plusMethodDouble(double x, double y) {
return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Instead of defining two methods that should do the same thing, it is better to
overload one.
In the example below, we overload the plusMethod method to work for
both int and double:
Example
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}

Note: Multiple methods can have the same name as long as the number and/or
type of parameters are different.

What is Operator Overloading?


Operator overloading allows operators to be redefined and used in a way where
they have a different meaning based on their operands. This feature can make the
code more intuitive and closer to the problem domain.
Such as + operator in java is use for addition as well as for concatenation in
output function.

Java Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes


and methods from another class. Polymorphism uses those methods to perform
different tasks. This allows us to perform a single action in different ways.

Example of Method Overloading


1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4. =============================================
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);
8. obj.sum(20,20,20);
9. }
10.}

Java Inheritance (Subclass and Superclass)


In Java, it is possible to inherit attributes and methods from one class to another.
We group the "inheritance concept" into two categories:
 subclass (child) - the class that inherits from another class
 superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass):

The syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10.d.bark();
11.d.eat();
12.}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10.class TestInheritance2{
11.public static void main(String args[]){
12.BabyDog d=new BabyDog();
13.d.weep();
14.d.bark();
15.d.eat();
16.}}
Output:

weeping...
barking...
eating...

Abstract Class in Java


An abstract class in Java acts as a partially implemented class that itself cannot be
instantiated. It exists only for subclassing purposes, and provides a template for
its subcategories to follow. Abstract classes can have implementations with
abstract methods. Abstract methods are declared to have no body, leaving their
implementation to subclasses.
Points to Remember

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the
body of the method.
o Example of Abstract Class that has an Abstract Method
o In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda class.
o abstract class Bike{
o abstract void run();
o }
o class Honda4 extends Bike{
o void run(){System.out.println("running safely");}
o public static void main(String args[]){
o Bike obj = new Honda4();
o obj.run();
o }
o }

Interface in Java
you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Java Interface Example
In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11.}

Generics in Java

Generics in Java are often considered Java's version of templates (especially when
compared to C++ templates). They enable classes, interfaces, and methods to
operate on different types while enforcing type safety at compile-time. Using
generics helps avoid the need for casting and reduces the likelihood of runtime
ClassCastException errors.

Key Points of Generics:

 Type Parameters: Generics use type parameters (like <T>, <E>, <K, V>, etc.)
to represent a placeholder type.
 Type Safety: Generics provide compile-time type checking, ensuring that
objects of a specific type are used where required.
Template Method Design Pattern

The Template Method is a design pattern in Java that defines the overall
structure (template) of an algorithm in a superclass while allowing subclasses to
provide specific implementations for certain steps. This pattern is part of the
behavioral patterns in the Gang of Four (GoF) design patterns.

Key Points of the Template Method Pattern:

 Template Method: The base class provides the core structure of the
algorithm in a method, often marked as final to prevent overriding.
 Hook Methods: Steps that can be customized by subclasses to provide
specific behaviors without changing the template.
 Code Reusability: By implementing core logic in a base class, we avoid
duplicating code in subclasses.

Example of the Template Method Pattern

Suppose we are creating a template for different types of games, where the
structure (start, play, end) is the same, but each game has its own way of playing.

java
Copy code
// Abstract class defining the template method
abstract class Game {
// Template method defining the sequence of steps
public final void playGame() {
startGame();
play();
endGame();
}

// Common method
private void startGame() {
System.out.println("Game is starting...");
}
Serialization and Deserialization in Java with Example



Serialization is a mechanism of converting the state of an object into a byte


stream. Deserialization is the reverse process where the byte stream is used to
recreate the actual Java object in memory. This mechanism is used to persist the

object.
Points to remember
1. If a parent class has implemented Serializable interface then child class
doesn’t need to implement it but vice-versa is not true.
2. Only non-static data members are saved via Serialization process.
3. Static data members and transient data members are not saved via
Serialization process. So, if you don’t want to save value of a non-static data
member then make it transient.
4. Constructor of object is never called when an object is deserialized.
5. Associated objects must be implementing Serializable interface
Standard Template Library (STL)

"A container is a holder object that stores a collection of other objects (its
elements). They are implemented as class templates, which allows a great
flexibility in the types supported as elements." The following links are excellent
resources describing the STL.

 Standard Containers
 The C++ Standard Template Library (STL)
o Algorithms
o Containers
o Functions
o Iterators

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10.}
Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a


try-catch block.

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are
as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.


there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider
the following statements.
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Java Exceptions Index

You might also like