0% found this document useful (0 votes)
13 views

Java

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Hierarchical abstractions

Hierarchical abstractions in computer science, particularly in object-oriented programming (OOP), refer to the
structured organization of classes and interfaces in a way that establishes a hierarchy. This hierarchy models
relationships and levels of abstraction, allowing developers to manage complexity by breaking down a system into
CLASS
INHERITANCE

POLYMORPHISM ABSTRACT CLASS

INTERFACES

more manageable pieces.

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body). Abstraction is a process of hiding the
implementation details and showing only functionality to the user.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
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.

BENEFITS OF HIERACHIAL ABSTRACTIONS :


Hierarchical abstractions provide several key benefits in software development, especially in object-oriented
programming (OOP). These benefits help manage complexity, improve code quality, and enhance maintainability. Here
are the primary advantages:

Modularity:

Definition: Modularity is the division of a software system into distinct, manageable sections or modules.

Benefit: Hierarchical abstractions break down complex systems into smaller, self-contained units, making the codebase easier to
understand, develop, and test. Each module can be developed and maintained independently, improving overall productivity.

Reusability
Definition: Reusability refers to the ability to use existing components or code in new applications or contexts.

Benefit: Common functionality defined in higher-level abstractions (superclasses or interfaces) can be reused across multiple
lower-level classes (subclasses). This reduces duplication and allows developers to leverage existing code, saving time and effort.

Maintainability
Definition: Maintainability is the ease with which a software system can be modified to fix defects, improve performance, or
adapt to a changed environment.

Benefit: Changes made to higher-level abstractions propagate to all subclasses, reducing the amount of code that needs to be
modified. This centralization of common behavior Extensibility

Extensibility
Definition: Extensibility is the ability to extend a system's functionality without modifying existing code.

Benefit: Hierarchical abstractions make it easy to add new functionality by introducing new subclasses or interfaces. This allows
for the seamless integration of new features and adaptations without disrupting the existing system.simplifies maintenance and
minimizes the risk of introducing errors.
Consistency
Benefit: Hierarchical abstractions enforce consistent behavior across different parts of the system. Subclasses inherit
behavior from their parent classes, ensuring that similar objects behave in predictable ways. This consistency is crucial
for reliable software behavior.

Code Clarity and Readability


Benefit: Well-defined hierarchical abstractions make the code more readable and easier to follow. Developers can
quickly understand the relationships between different components, leading to more efficient code reviews and
collaborative development.

Hierarchical abstractions provide a framework for organizing and managing complex software systems. By leveraging
inheritance, abstraction, and polymorphism, they offer numerous benefits, including modularity, reusability,
maintainability, extensibility, flexibility, encapsulation, improved design, reduced complexity, code clarity, and
consistency. These advantages contribute to the development of robust, scalable, and maintainable software
solutions

Types of Inheritance in Java


Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. A class whose properties are inherited is known as parent class and a class that inherits the properties
of the parent class is known as child class. Thus, it establishes a relationship between parent and child class
that is known as parent-child or Is-a relationship. A class whose properties are inherited is known as parent
class and a class that inherits the properties of the parent class is known as child class. Thus, it establishes a
relationship between parent and child class that is known as parent-child or Is-a relationship.

When we should use inheritance?


Inheritance provides the reusability of code especially when there is a large scale of code to reuse. It also
establishes the relationship between different classes that is known as a Is-a relationship. We can also use it
if we want to achieve method overriding.

.
Points to Remember
o Constructor cannot be inherited in Java.
o Private members do not get inherited in Java.
o Cyclic inheritance is not permitted in Java.
o Assign parent reference to child objects.
o Constructors get executed because of super() present in the constructor.

Java supports the following four types of inheritance:

o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance

In single inheritance, a sub-class is derived from only one super class.

a class that has more than one parent class is called multi-level inheritance

If a number of classes are derived from a single base class, it is called hierarchical inheritance.

Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more types of inheritance

Multiple Inheritance (not supported)


Java does not support multiple inheritances due to ambiguity. For example, consider the following Java
program.
Classes in Java
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:

Modifiers: A class can be public or has default access (Refer to this for details).

Class name: The name should begin with an initial letter (capitalized by convention).

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.

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.

Body: The class body surrounded by braces, { }.

Interface in Java
Like a class, an interface can have methods and variables, but the methods declared in the interface are by default abstract
(only method signature, nobody).

Interfaces specify what a class must do and not how. It is the blueprint of the class.

An Interface is about capabilities like a Player may be an interface and any class implementing Player must be able to (or must
implement) move(). So it specifies a set of methods that the class has to implement.

If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the
class must be declared abstract.

A Java library example is Comparator Interface. If a class implements this interface, then it can be used to sort a collection.
Class Interface

The keyword used to create a class is The keyword used to create an interface is
“class” “interface”

A class can be instantiated i.e., objects of a An Interface cannot be instantiated i.e. objects
class can be created. cannot be created.

Classes do not support multiple inheritance. The interface supports multiple inheritance.

It can be inherited from another class. It cannot inherit a class.

It can be inherited by a class by using the keyword


It can be inherited by another class using
‘implements’ and it can be inherited by an interface
the keyword ‘extends’.
using the keyword ‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be


All variables and methods in an interface are
declared using any access specifier(public,
declared as public.
private, default, protected).

Variables in a class can be static, final, or


All variables are static and final.
neither.

Variables in interfaces :
variables declared in an interface are implicitly public, static, and final. This means they are constants that
belong to the interface itself, not to any instance of a class that implements the interface they cannto be changed if
you try to change it throws error.
Benefits of Inheritance
Code Reusability
Reuse Existing Code: Inheritance allows a class to reuse code from an existing class. This reduces redundancy and leads to less
duplicated code, making the codebase more efficient and easier to manage.

Example: If multiple classes need similar functionality, you can put that functionality in a base class and have other classes
inherit from it. of inheritance :

Code Maintenance

Centralized Updates: When a change is made in the superclass, it automatically propagates to all subclasses. This makes it easier
to maintain and update code, as changes need to be made in only one place.

Consistency: Ensures consistency across all subclasses since they share the same implementation from the superclass.

Extensibility

Easier to Extend Functionality: Inheritance allows for the creation of new classes that build upon existing classes. This makes it
easy to extend functionality without modifying existing code.

Example: You can create new subclasses to add or override functionality as neededPolymorphism

Dynamic Method Dispatch: Inheritance supports polymorphism, which allows a subclass to be treated as an instance of its
superclass. This enables the writing of more generic and reusable code.

Example: You can write methods that operate on superclass types but can work with any subclass instance.

Hierarchical Classification

Logical Structure: Inheritance helps create a hierarchical structure for classifying objects. This mirrors real-world relationships
and logical groupings, making the system more intuitive.

Example: A hierarchy of classes like Vehicle -> Car -> ElectricCar logically organizes different types of vehicles and their specific
characteristics.

Abstraction

Simplification: Inheritance helps abstract common features into a base class, simplifying the representation of complex systems.
This reduces complexity by focusing on high-level concepts and relationships.

Example: Abstracting common attributes and behaviors into a base class makes the system easier to understand and manage.

Inheritance provides numerous benefits, including code reusability, ease of maintenance, extensibility, support for
polymorphism, logical classification, abstraction, and enhanced encapsulation. These advantages contribute to
creating modular, maintainable, and scalable software systems. By leveraging inheritance, developers can build robust
and flexible applications that are easier to understand, extend, and maintain.
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
In Java, the this keyword is a reference variable that refers to the current object instance within an
instance method or constructor. It is used to distinguish between instance variables and
parameters, invoke other constructors in the same class, and provide a reference to the current
object.

Uses of this Keyword in Java

The this keyword has several uses in Java, each enhancing code clarity and functionality. Here are
the primary uses:

1. Referencing Instance Variables

When local variables (such as parameters in a constructor or method) have the same names as
instance variables, the this keyword is used to differentiate between them. This clarifies that the
instance variable, rather than the local variable, is being referenced.

2.Invoking Instance Methods


The this keyword can be used to call another method within the same class. This helps in method
chaining and avoids ambiguity. If you don't use the this keyword, compiler automatically adds this

keyword while invoking the method. Let's see the example


TO INVOKE CURRENT CLASS CONSTRUCTOR :
Calling Another Constructor in the Same Class.This is known as constructor chaining. The
this keyword is used to call one constructor from another, reducing codPassing the
Current Instance as an Argument

class A{

A(){System.out.println("hello a");}

1. A(int x){
2. this();
3. System.out.println(x);
4. }
5. }
6. class TestThis5{
7. public static void main(String args[]){
8. A a=new A(10);
9. }}

Real usage of this() constructor call


The this() constructor call should be used to reuse the constructor from the constructor. It maintains the
chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below
that displays the actual use of this keyword.

1. class Student{ 10. Student(int rollno,String name,String course,float fee){


2. int rollno; this(rollno,name,course);//reusing constructor
3. String name,course; 11. this.fee=fee;
4. float fee; }
5. Student(int rollno,String name,String course){ void display(){System.out.println(rollno+"
6. this.rollno=rollno; "+name+" "+course+" "+fee);}
7. this.name=name; } class TestThis7{
8. this.course=course; public static void main(String args[]){
9. } Student s1=new Student(111,"ankit","java");
12. Student s2=new Student(112,"sumit","java",6000f);
13. s1.display();
Java super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class object.Whenever you create the
instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1. class TestSuper3{
1. class Animal{
2. public static void main(String args[]){
2. Animal(){System.out.println("animal is created");}
3. Dog d=new Dog();
4. }}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
USES OF INHERITANCE IN JAVA :
CODE REUSABILITY

Inheritance allows a new class (child class or subclass) to inherit properties and methods from an existing class (parent
class or superclass). This promotes code reuse, as common functionality need not be rewritten for each new class.

METHOD OVERRIDING

Inheritance enables method overriding, which allows a subclass to provide a specific implementation of a method that is
already defined in its superclass. This helps in implementing polymorphism.

IMPROVED CODE MAINTAINABILITY

By organizing code using inheritance, modifications and updates become easier. Changes in the superclass can propagate
to subclasses, reducing the amount of code that needs to be altered.

ENHANCED EXTENSIBILITY

Inheritance makes it easier to extend existing code. New functionality can be added by creating subclasses that build
upon the existing functionality of the super class.

ENCAPSULATION AND ABSTRACTION

Inheritance supports encapsulation and abstraction. Superclasses can define the common interface and hide
implementation details, while subclasses can extend and customize the behavior as needed.e superclass.

IMPROVED TESTING AND DEBUGGING

With a well-structured inheritance hierarchy, testing and debugging become more straightforward. Bugs can be traced
more easily because functionality is inherited, and common behavior is centralized.

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be
categorized in two form, built-in package and user-defined package.There are many built-in packages such as
java, lang, awt, javax, swing, net, io, util, sql etc

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.


3) Java package removes naming collision.

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

USING PACKAGENAME .*

If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.The import
keyword is used to make the classes and interface of another package accessible to the current package.

USING PACKAGENAME .CLASSNAME

If you import package.classname then only declared class of this package will be accessible.

USING FULLY QUALIFIED NAME

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But
you need to use fully qualified name every time when you are accessing the class or interface.

PROPERTIES OF AN INTERFACE

An Interfaces have the following properties:

An interface is implicitly pure abstract.

No need to use the abstract keyword while declaring an interface

Each method in an interface is also implicitly abstract, so the abstract keyword is not needed

The Methods in an interface are implicitly public within it


Types of Interfaces
Functional Interface

Marker interface

Built-in Marker Interface

There are three types of Built-In Marker Interfaces in Java. These are

Constructors in Java
A constructor is a special type of method which is used to initilise the object it is called when an instance of a class is created.
At the time of calling constructor, memory for the object is allocated in the memory. Every time an object is created using the
new() keyword, at least one constructor is called.It calls a default constructor if there is no constructor available in the class.
In such case, Java compiler provides a default constructor by default.

It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor
for a class. It is because java compiler creates a default constructor if your class doesn't have any.

There are two rules defined for the constructor.

Constructor name must be the same as its class name

A Constructor must have no explicit return type

A Java constructor cannot be abstract, static, final, and synchronized


Types of Java constructors
There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you can
provide the same values also.

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.

Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.
Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you don't The method is not provided by the
have any constructor in a class. compiler in any case.

The constructor name must be same as the class name. The method name may or ma

Java Garbage Collection


In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is
a way to destroy the unused objects.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.

How can an object be unreferenced?


o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.

By nulling a reference:
1. Employee e=new Employee();
2. e=null;
By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection

By anonymous object:
1. new Employee();

finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be used
to perform cleanup processing. This method is defined in Object class as:

protected void finalize(){}

The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have
created any object without new, you can use finalize method to perform cleanup processing (destroying
remaining objects).

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in
System and Runtime classes.

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the
finalize() method before object is garbage collected.
1. public class TestGarbage1{
2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10. }

You might also like