introduction to object oriented programing-java-4th-sem
introduction to object oriented programing-java-4th-sem
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:
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
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.
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.
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
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;
}
Note: Multiple methods can have the same name as long as the number and/or
type of parameters are different.
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
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...
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.
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.
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.
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.
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
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
In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime.
JavaExceptionExample.java
Output:
1. int a=50/0;//ArithmeticException
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
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException