Java
Java
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
INTERFACES
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.
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
.
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.
o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
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
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.
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.
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.
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.
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.
The this keyword has several uses in Java, each enhancing code clarity and functionality. Here are
the primary uses:
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.
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. }}
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.
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.
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.
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
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
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.
If you import package.classname then only declared class of this package will be accessible.
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
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed
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.
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
The parameterized constructor is used to provide different values to distinct objects. However, you can
provide the same values also.
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.
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 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
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is
a way to destroy the unused objects.
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:
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. }