0% found this document useful (0 votes)
8 views38 pages

UNIT-2 Java Programming Notes

The document covers key concepts in Java programming, including user-defined classes, objects, arrays, constructors, and inheritance. It explains the structure and behavior of Java classes, the creation and initialization of objects, and the types and advantages of arrays. Additionally, it details constructors, their types, and the inheritance mechanism in Java, including different types of inheritance and the use of the final keyword.

Uploaded by

jananippriya18
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)
8 views38 pages

UNIT-2 Java Programming Notes

The document covers key concepts in Java programming, including user-defined classes, objects, arrays, constructors, and inheritance. It explains the structure and behavior of Java classes, the creation and initialization of objects, and the types and advantages of arrays. Additionally, it details constructors, their types, and the inheritance mechanism in Java, including different types of inheritance and the use of the final keyword.

Uploaded by

jananippriya18
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/ 38

Java Programming--- 225C3A

UNIT-2
Java user defined Classes and Objects – Arrays – constructors - Inheritance: Basic concepts - Types of
inheritance - Member access rules - Usage of this and Super key word - Method Overloading -
Method overriding - Abstract classes - Dynamic method dispatch - Usage of final keyword -Packages:
Definition - Access Protection - Importing Packages - Interfaces: Definition – Implementation –
Extending Interfaces

Java Class
A Java classes is a blueprint or template used to create object. It serves as a fundamental building
block in Java programming, encapsulating data (fields) and behaviors (methods) into a single unit.

a Java class defines the structure and behavior of objects, serving as a blueprint for creating
instances of that class.

Properties of Java Classes

 A Java class serves as a blueprint for creating objects and doesn’t take up memory.

 It comprises variables of various types and methods. You can include data members,
methods, constructors, nested classes, and interfaces within a class.

 It acts as a template for organizing and defining the behaviour of objects in your program.

Syntax of Java Classes

package com.example;

import java.util.ArrayList;

public class MyClass {

private int age;

public MyClass(int age) {

this.age = age;

public void display() {

System.out.println("Age: " + age);

}
This syntax defines a class named MyClass in the com.example package, with a private
field age, a constructor that initializes age, and a method display() to print the age.

Components of Java Class

In Java, a class serves as a blueprint for creating objects. It encapsulates data and behavior
into a single unit. Here are the main components of a Java class:

 Class Declaration: The class declaration defines the name of the class and any inheritance or
interfaces it implements.

public class MyClass {

// class body

 Fields (Instance Variables): Fields represent the state or attributes of objects created from
the class.

private int age;

 Constructors: Constructors initialize objects of the class. They have the same name as the
class and are called when objects are created.
public MyClass(int age) {
this.age = age;
}
 Methods define the behavior or actions that objects of the class can perfor
public void display() {
System.out.println("Age: " + age);
}
 Access Modifiers: Access modifiers control the accessibility of class members (fields,
constructors, methods).
public class MyClass {
private int age;
public MyClass(int age)
this.age = age;
}
public void display() {
System.out.println("Age: " + age);
}
}

Rules for creating a class


In order to create a class, these rules must be followed-
 The “class” keyword should be used.
 The name of the class should start with an uppercase letter.
 The Java file can contain any number of classes but should not have more than one public
class. The file name should be named after the public class followed by the “.java” extension.
 One class should only inherit another single class.
Types of classes
There are two types of classes-
1. Built-in classes
2. User-defined classes

 Built-in classes- The built-in classes are those which are pre-defined by the developers
in JDK.
Examples include-
java.util.Date

java.util.LinkedList

 User-defined classes- So as the name suggests, user-defined classes are the classes created
by the user. We can add our functionality to the classes.

Java Objects

 A Java object is an instance of a class. It represents a specific


realization of the class blueprint, with its own unique set of data
values for the fields defined in the class.
 Objects are created using the new keyword followed by the
class name, along with any required arguments to initialize the
object’s state. Each object created from a class has its own separate
memory space allocated for its fields, allowing it to maintain its own
state independent of other objects created from the same class
An object consists of :
1. State: It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects
the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to
interact with other objects.

Syntax of an object
The syntax for creating an object in Java is:
ClassName objectName = new ClassName();
Car myCar = new Car();
Here, Car is the class name, myCar is the object name, and new
Car() instantiates a new object of the Car class.
Initializing an object
In Java, we can initialize objects in 3 ways-
 By reference variable
 By method
 By constructor
By reference variable– Initialization of an object means storing the data in
the object. Let us understand this with an example-
public class MyClass {
public static void main(String[] args) {
// Initialize the object by reference variable in a single line
MyClass myObject = new MyClass();

// Access methods or fields of the object


myObject.myMethod();
}

public void myMethod() {


System.out.println("Object initialized successfully!");
}
}
Difference Between Java Classes and Object

Arrays in Java
What is an Array in Java?

An array refers to a data structure that contains homogeneous elements. This means that all
the elements in the array are of the same data type. Let's take an example:

There are three main features of an array:

1. Dynamic allocation: In arrays, the memory is created dynamically, which reduces the amount
of storage required for the code.
2. Elements stored under a single name: All the elements are stored under one name. This
name is used any time we use an array.
3. Occupies contiguous location: The elements in the arrays are stored at adjacent positions.
This makes it easy for the user to find the locations of its elements.

Advantages of Arrays in Java


 Java arrays enable you to access any element randomly with the help of indexes
 It is easy to store and manipulate large data sets
Disadvantages of Arrays in Java
 The size of the array cannot be increased or decreased once it is declared—arrays have a
fixed size
 Java cannot store heterogeneous data. It can only store a single type of primitives
Now that we understand what Java arrays are- let us look at how arrays in Java are declared
and defined.

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

To declare an array, define the variable type with square brackets:


String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, you can
place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:


int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array

You can access an array element by referring to the index number.


This statement accesses the value of the first element in cars:

Example:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);
// Outputs Volvo

Change an Array Element

To change the value of a specific element, refer to the index number:


Example
cars[0] = "Opel";

Array Length
To find out how many elements an array has, use the length property:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars.length);
// Outputs 4
Types of Arrays
There are three types of arrays. We use these types of arrays as per the requirement of the
program. These are:
1. One-dimensional Array
Also known as a linear array, the elements are stored in a single row. For example:

In this example, we have an array of five elements. They are stored in a single line or
adjacent memory locations.

Look at this example in Java code. Here, the five elements are 1, 2, 3, 4, and 5. We use a for
loop to print the elements of the array. The output of this is as follows:
2. Two-dimensional Array
Two-dimensional arrays store the data in rows and columns:

In this, the array has two rows and five columns. The index starts from 0,0 in the left-upper
corner to 1,4 in the right lower corner.
In this Java code, we have a two-dimensional array. We have two rows and three columns.
Brackets separate the rows, and the number of elements separates the columns. For this, we
use two for loops: one for rows and one for each element in the row. When we execute this
program, the result will be as follows:

3. Multi-dimensional Array
This is a combination of two or more arrays or nested arrays. We can even use more than
two rows and columns using the following code:
Here, we are using three rows and three columns, but we are only using two for loops.
Regardless of how many rows and columns are entered, the number of for loops will always
be two.
The above program will add all the elements defined in my_array[] and produce the result.

Constructors in Java
In Java, a Constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling the constructor, memory for the object is
allocated in the memory. It is a special type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
Syntax
public class MyClass {
// Constructor
public MyClass() {
// Initialization code goes here
}

// Other methods and variables can be defined here


}

Rules for creating Java constructor


There are two rules defined for the constructor.
1. The constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java Constructors

 Default constructor: These constructors do not accept any parameters.


 Parameterized constructor: These constructors accept a specific number of parameters.
Default Constructor
 In Java, if a class does not explicitly define any constructors, the
compiler automatically provides a default constructor. This default
constructor is parameterless (i.e., it takes no arguments) and
initializes member variables to their default values.
 Here’s an example of a default constructor in Java:

public class MyClass {

private int myInt;

private String myString;

// This class does not define any constructors

public static void main(String[] args) {

// Creating an object of MyClass using the default constructor

MyClass obj = new MyClass();

// Accessing member variables

System.out.println("Default value of myInt: " + obj.myInt);

// Output: Default value of myInt: 0

System.out.println("Default value of myString: " + obj.myString);

// Output: Default value of myString: null

Parameterized Constructor

A parameterized constructor in Java is a constructor that accepts one or more parameters,


allowing you to initialize objects with specific values. Unlike the default constructor, which
takes no arguments, a parameterized constructor allows you to pass values at the time of
object creation to set initial states.
Here’s an example of a parameterized constructor in Java:

public class MyClass {


private int myInt;
private String myString;

// Parameterized constructor
public MyClass(int intValue, String stringValue) {
myInt = intValue;
myString = stringValue;
}

// Method to display values


public void displayValues() {
System.out.println("myInt: " + myInt);
System.out.println("myString: " + myString);
}

public static void main(String[] args) {


// Creating an object of MyClass using the parameterized constructor
MyClass obj = new MyClass(10, "Hello");

// Displaying the initialized values


obj.displayValues();
}
}

Constructor Overloading in Java

In Java, constructors are similar to methods but without a return type. They can be
overloaded, just like methods, allowing for the creation of multiple constructors with
different parameter lists. Each constructor can serve a distinct purpose, with the compiler
distinguishing them based on the number and types of parameters they accept. This
technique, known as constructor overloading, enables flexibility in initializing objects based
on varying sets of input parameters.

class Dogs {

private String name;


private String breed;

public Dogs() {
// No initialization parameters
}
public Dogs(String breed) {
this.breed = breed;
}

public Dogs(String name, String breed) {


this.name = name;
this.breed = breed;
}

void isRunning(int runStatus) {


if (runStatus == 1) {
System.out.println("Dog is running");
} else {
System.out.println("Dog is not running");
}
}

public class Main {

public static void main(String[] args) {


Dogs dog1 = new Dogs();
Dogs dog2 = new Dogs("Bulldog");

dog1.isRunning(0);
dog2.tailWagging("Woof");

// A dog with both name and breed initialized at the time of object creation.
Dogs dog3 = new Dogs("Snoopy", "German Shepherd");
}
}

Output:
Dog is not running
Dog is wagging its tail

Copy Constructor in Java

A Copy Constructor in Java is used to create an object with the help of another object of the
same Java class.
The copy constructor has at least one object of the same class as an argument. The primary
objective of the copy constructor is to create a new object with the same properties as that
of the passed argument.

public class MyClass {


private int myInt;
private String myString;

// Copy constructor
public MyClass(MyClass original) {
this.myInt = original.myInt;
this.myString = original.myString;
}

// Parameterized constructor
public MyClass(int intValue, String stringValue) {
this.myInt = intValue;
this.myString = stringValue;
}

// Method to display values


public void displayValues() {
System.out.println("myInt: " + myInt);
System.out.println("myString: " + myString);
}

public static void main(String[] args) {


// Creating an object of MyClass
MyClass originalObj = new MyClass(10, "Hello");

// Creating a copy of originalObj using the copy constructor


MyClass copiedObj = new MyClass(originalObj);

// Displaying values of both objects


System.out.println("Original Object:");
originalObj.displayValues();

System.out.println("nCopied Object:");
copiedObj.displayValues();
}
}

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):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();

// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:
final class Vehicle {
...
}

class Car extends Vehicle {


...
}

The 5 types of inheritance related to Java are given below:


 Single-level inheritance
 Multi-level Inheritance
 Hierarchical Inheritance
 Multiple Inheritance
 Hybrid Inheritance

1. Single-level inheritance
Single-level inheritance in Java is a fundamental concept where a subclass inherits from only
one superclass. This means that the subclass can acquire the properties and methods of the
superclass, enabling code reuse and the extension of existing functionality.
A graphical illustration of single-level inheritance is given below:

2. Multi-level Inheritance
Multilevel inheritance in Java is a feature that allows a class to inherit properties and
behaviours from another class, which in turn inherits from another class, forming a "chain"
of inheritance. This mechanism enables a class to inherit methods and fields from multiple
ancestors but in a direct line, where each class in the chain inherits from one class directly
above it.

A graphical illustration of multi-level inheritance is given below:

3. Hierarchical Inheritance
Hierarchical inheritance in Java occurs when one base class (superclass) is inherited by
multiple subclasses. In this type of inheritance, all the features that are common in child
classes are included in the base class. This way, the code becomes more manageable and
reusable.

A graphical illustration of hierarchical inheritance is given below:


4. Multiple Inheritance
Multiple inheritance refers to a feature in object-oriented programming where a class can
inherit properties and methods from more than one parent class. This concept allows a
subclass to inherit behaviours and attributes from multiple base (or super) classes, creating a
rich, multifaceted hierarchy.

A graphical illustration of multiple inheritance is given below:

Instead of multiple inheritance for classes, Java provides a mechanism to achieve


polymorphism and code reuse through interfaces.

An interface in Java is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot
contain instance fields or constructor methods.

A class in Java can implement multiple interfaces, allowing it to inherit abstract methods
from multiple sources.

5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance, such as
hierarchical, multiple, multilevel, or single inheritance. It integrates various inheritance
mechanisms to achieve a specific design or functionality
A graphical illustration of hybrid inheritance is given below:

Java Access Modifiers

What are Access Modifiers?


In Java, access modifiers are used to set the accessibility (visibility)
of classes, interfaces, variables, methods, constructors, data members, and the setter
methods.

Types of Access Modifier

Modifier Description

declarations are visible only within the package


Default
(package private)

Private declarations are visible within the class only

Protecte declarations are visible within the package or all


d subclasses

Public declarations are visible everywhere

Public Access Modifier

When methods, variables, classes, and so on are declared public, then we can access
them from anywhere. The public access modifier has no scope restriction.
// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;

// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}

// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();

// accessing the public variable


animal.legCount = 4;
// accessing the public method
animal.display();
}
}

Output:
I am an animal.
I have 4 legs.

Private Access Modifier

When variables and methods are declared private, they cannot be accessed outside
of the class.

For example,

class Data {
// private variable
private String name;
}
public class Main {
public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class


d.name = "Programiz";
}
}

Output:
The name is Programiz

Protected Access Modifier

When methods and data members are declared protected, we can access them
within the same package as well as from subclasses.

For example,

class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}

class Dog extends Animal {


public static void main(String[] args) {

// create an object of Dog class


Dog dog = new Dog();
// access protected method
dog.display();
}
}

Output:
I am an animal
Default Access Modifier

If we do not explicitly specify any access modifier for classes, methods, variables, etc,
then by default the default access modifier is considered.

package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}

Usage of Super and This Keywords in Java

“Super” Keyword in Java


In Java, the super keyword is a reference variable that refers to the
immediate superclass/parent class objects if using the keyword inside the child
class.

Uses of super Keyword in Java:

 Access Parent Class Variables: When a child class has a variable with the same name
as its parent class, super helps access the parent’s variable.
 Call Parent Class Methods: If a child class overrides a method from its parent, super
allows calling the parent class’s version of the method.
 Invoke Parent Class Constructor: super() can be used to call the parent class
constructor from a child class constructor.
 Differentiate Between Parent and Child Class Members: It helps when both parent
and child classes have members with the same name.
 Improve Code Reusability: By using super, we can reuse parent class functionalities
instead of rewriting code in the child class.

Syntax
super();
super.methodName();
super.fieldName;

1. Calling Superclass Constructor

In this example, the super() call in the Dog constructor invokes the
constructor of the Animal class.
Example 1: Calling Superclass Constructor
class Animal {

class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}

class Dog extends Animal {


Dog() {
super(); // Calls the constructor of Animal class
System.out.println("Dog constructor called");
}
}

public class TestSuper {


public static void main(String[] args) {
Dog d = new Dog(); // Output: Animal constructor called
// Dog constructor called
}
}

Example 2: Accessing Superclass Method

Here, the super.sound() call in the Dog class method sound() invokes
the sound() method of the Animal class.

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
super.sound(); // Calls the sound() method of Animal class
System.out.println("Dog barks");
}
}

public class TestSuper {


public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Output: Animal makes a sound
// Dog barks
}
}

Example 3: Accessing Superclass Field

In this example, super.color is used to access the color field of


the Animal class, which is hidden by the color field in the Dog class.

class Animal {
String color = "white";
}
class Dog extends Animal {
String color = "black";

void displayColor() {
System.out.println("Dog color: " +// Prints the color of Dog class
System.out.println("Animal color: " + super.// Prints the color of
Animal class
}
}
public class TestSuper {
public static void main(String[] args) {
Dog d = new Dog();
d.displayColor(); // Output: Dog color: black
// Animal color: white
}
this keyword
this keyword:
It is a reserved keyword in Java that is used to refer to the current class object. It is a
reference variable through which the method is called. Other uses of this keyword
are:
o We can use it to refer current class instance variable.
o We can use it to invoke the current class method (implicitly).
o We can pass it as an argument in the method and constructor calls.
o We can also use it for returning the current class instance from the method.

Difference Between this and super keyword


o The following table describes the key difference between this
and super:

this super

The current instance of the class is The current instance of the parent class is
represented by this keyword. represented by the super keyword.

In order to call the default constructor of the In order to call the default constructor of the
current class, we can use this keyword. parent class, we can use the super keyword.

It can be referred to from a static context. It It can't be referred to from a static context. It
means it can be invoked from the static means it cannot be invoked from a static
context. context.

We can use it to access only the current class We can use it to access the data members and
data members and member functions. member functions of the parent class.

Java Method Overriding


Method overriding allows us to achieve run-time polymorphism and is used for writing specific
definitions of a subclass method that is already defined in the superclass.

The method is superclass and overridden method in the subclass should have the same declaration
signature such as parameters list, type, and return type.
Usage of Java Method Overriding

Following are the two important usages of method overriding in Java:

 Method overriding is used for achieving run-time polymorphism.

 Method overriding is used for writing specific definition of a subclass method (this method is
known as the overridden method).

Rules for Method Overriding

 The argument list should be exactly the same as that of the overridden method.

 The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.

 The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the sub
class cannot be either private or protected.

 Instance methods can be overridden only if they are inherited by the subclass.

 A method declared final cannot be overridden.

 A method declared static cannot be overridden but can be re-declared.

 If a method cannot be inherited, then it cannot be overridden.

 A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.

 A subclass in a different package can only override the non-final methods declared public or
protected.

 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the overridden
method. The overriding method can throw narrower or fewer exceptions than the
overridden method.

 Constructors cannot be overridden.

Java Method Overriding: Using the super


Keyword
Example: Using the super Keyword

class Animal {
public void move()

System.out.println("Animals can move");

class Dog extends Animal { public void move()

super.move();

// invokes the super class method

System.out.println("Dogs can walk and run");

public class TestDog {

public static void main(String args[])

Animal b = new Dog();

// Animal reference but Dog object

b.move();

// runs the method in Dog class

Output

Animals can move

Dogs can walk and run

Java Method Overloading


In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called overloaded
methods and this feature is called method overloading. For example:

void func() { ... }

void func(int a) { ... }


float func(double a) { ... }

float func(int a, float b) { ... }

Here are different ways to perform method overloading:

1. Overloading by changing the number of parameters

class MethodOverloading {

private static void display(int a){

System.out.println("Arguments: " + a);

private static void display(int a, int b){

System.out.println("Arguments: " + a + " and " + b);

public static void main(String[] args) {

display(1);

display(1, 4);

Output:

Arguments: 1

Arguments: 1 and 4

2. Method Overloading by changing the data type of parameters

class MethodOverloading {

// this method accepts int

private static void display(int a){

System.out.println("Got Integer data.");

// this method accepts String object

private static void display(String a){


System.out.println("Got String object.");

public static void main(String[] args) {

display(1);

display("Hello");

Output:

Got Integer data.

Got String object.

Here, both overloaded methods accept one argument. However, one accepts the argument of
type int whereas other accepts String object.

Important Points

 Two or more methods can have the same name inside the same class if they accept different
arguments. This feature is known as method overloading.

 Method overloading is achieved by either:

o changing the number of arguments.

o or changing the data type of arguments.

 It is not method overloading if we only change the return type of methods. There must be
differences in the number of parameters.
Difference between method overloading and method overriding:

Java Abstraction

Abstract Classes and Methods

The abstract keyword is a non-access modifier, used for classes and methods:

 Abstract class: is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).

 Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods:


abstract class Animal {

public abstract void animalSound();

public void sleep() {

System.out.println("Zzz");

Java Polymorphism

Polymorphism in Java is a core concept of object-oriented programming (OOP) that allows objects to
be treated as instances of their parent class. It facilitates flexibility and the ability to define methods
in multiple forms. Polymorphism is primarily achieved through method overriding and method
overloading.

Usage

Polymorphism is used to perform a single action in different ways. It allows for the implementation
of dynamic method dispatch, where the method to be executed is determined at runtime. This is
beneficial for implementing a cleaner and more maintainable codebase.

Types of Polymorphism
1. Compile-time Polymorphism (Method Overloading): Achieved by defining multiple methods
with the same name but different parameters within the same class.

2. Runtime Polymorphism (Method Overriding): Achieved when a subclass provides a specific


implementation of a method already defined in its superclass.

Examples

Example 1: Method Overloading

public class OverloadingExample {

public int add(int a, int b) {

return a + b;

public double add(double a, double b) {

return a + b;
}

public static void main(String[] args) {

OverloadingExample obj = new OverloadingExample();

System.out.println("Sum of integers: " + obj.add(5, 10));

System.out.println("Sum of doubles: " + obj.add(5.5, 10.5));

In this example, the add method is overloaded with two different parameter lists. The appropriate
method is called based on the arguments passed.

Example 2: Method Overriding

class Animal {

public void sound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

@Override

public void sound() {

System.out.println("Dog barks");

public class OverridingExample {

public static void main(String[] args) {

Animal myAnimal = new Dog();

myAnimal.sound(); // Outputs "Dog barks"

Here, the Dog class overrides the sound method of the Animal class. The sound method of
the Dog class is invoked at runtime.
final Keyword in Java
The final keyword in Java is a non-access modifier that can be applied to variables, methods, and
classes. It is used to restrict the user from further modifying the entity to which it is applied. This
keyword plays a crucial role in ensuring immutability and preventing inheritance or method
overriding.

Usage:

1. final Variables

A final variable is a constant; once initialized, its value cannot be changed.

final int MAX_VALUE = 100;

Initialization of final Variables

A final variable must be initialized when it is declared or within a constructor if it is an instance


variable.

public class FinalInitialization {

final int MAX_VALUE;

public FinalInitialization() {

MAX_VALUE = 100;

Examples

Example 1: final Variable

public class FinalVariableExample {

public static void main(String[] args) {

final int MAX_VALUE = 100;

System.out.println("MAX_VALUE: " + MAX_VALUE);

// MAX_VALUE = 200; // This will cause a compilation error

}
2. final Methods

A final method cannot be overridden by subclasses, ensuring that the method's implementation
remains unchanged.

class Parent {

public final void display() {

System.out.println("This is a final method.");

Example 2: final Method

class Parent {

public final void display() {

System.out.println("This is a final method.");

class Child extends Parent {

// public void display() { // This will cause a compilation error

// System.out.println("Attempting to override.");

// }

public class FinalMethodExample {

public static void main(String[] args) {

Child obj = new Child();

obj.display();

3. final Classes

A final class cannot be subclassed, preventing inheritance.


public final class FinalClass {

// Class implementation

Example 3: final Class

public final class FinalClass {

public void show() {

System.out.println("This is a final class.");

// class SubClass extends FinalClass { // This will cause a compilation error

// }

public class FinalClassExample {

public static void main(String[] args) {

FinalClass obj = new FinalClass();

obj.show();

Packages in Java
A Java package is a group of similar types of classes, interfaces and sub-packages.

Organise Classes: For organizing the class, interfaces and other components, packages are used.
o Control Access: It is the package that controls the access of the protected and default
members. Think what would be the use of default and protected access specifiers if packages
were absent?

o Reusability: Java enhances the reusability management of code and does the promotion of
data encapsulation with the help of packages.

Types of Packages

There are two types of packages in Java.

1. Built-in Packages

2. User-defined Packages

1.Built-in Packages
Some of the built-in packages that are used commonly are:

java.lang: It contains those classes that are required for language support, such as classes for
primitive data types and math operations. This package is automatically imported into Java.

java.io: It contains all those classes that are required for the input/output operations.

java.util: It contains utility classes that are needed for the data structures, such as Array, List, Map,
etc.

java.applet: All those classes that are required for finding applets are found in this package.

java.awt: It contains all those classes that are required for creating components of GUI (Graphical
User Interface).

java.net: It includes classes that are used for doing tasks in the field of networking.

2.User-defined Packages
In this section, we will create two Java files in two different packages (or folders). We will also create
three files. One file each for both the folders, and the last file is of the main class.

How to Create a Package?

To create a package in Java, you use the `package` keyword. The package statement must be the first
line in the source file (excluding comments).
Creating a Package:

// File: com/example/HelloWorld.java
package com.example;

public class HelloWorld {


public void greet() {
System.out.println("Hello from the com.example package!");
}
}

In this example:

- The `package com.example;` statement defines that the class `HelloWorld` belongs to the
`com.example` package.

- The folder structure should mirror the package name (`com/example/`).

5. Accessing Classes from Packages

To access a class from a package, the fully qualified name of the class (including the package name)
should be used, or the class should be imported.

Accessing Without Import:

com.example.HelloWorld hello = new com.example.HelloWorld();


hello.greet();

6. Importing Packages

Java provides the `import` statement to import classes or entire packages.

1. Importing a Single Class:

import com.example.HelloWorld;

2. Importing All Classes in a Package:

import com.example.*;

In the second example, all classes within the `com.example` package will be imported.

7. Sub-packages in Java

Java supports sub-packages, which are simply packages within other packages. There is no special
syntax for sub-packages; they are treated like regular packages, but the hierarchy is created by
adding dots in the package name.

Example:

package com.example.utils;

8. Package Naming Conventions

Java follows certain conventions for naming packages to ensure uniqueness and clarity:
1. Reverse Domain Name: Use your domain name in reverse as the base of your package names. For
example, if your domain is `example.com`, start your package with `com.example`.

2. Lowercase Names: Use lowercase letters to avoid conflicts with class names.

3. Meaningful Names: Use descriptive and meaningful names to reflect the content of the package.

9. Java Built-in Packages

Java comes with several built-in packages that provide a wide range of functionalities. Some common
built-in packages are:

- java.lang: Provides classes fundamental to the Java language (automatically imported).

- java.util: Contains utility classes, including collections framework, date, time facilities, and more.

- java.io: Contains classes for input/output operations (e.g., file handling).

- java.net: Contains classes for networking operations.

- java.sql: Contains classes for database access and processing.

Java Interface
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
Relationship Between Class and Interface
A class can extend another class, and similarly, an interface can extend another interface.
However, only a class can implement an interface, and the reverse (an interface
implementing a class) is not allowed.
Notes on Interfaces:
 Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
 Interface methods do not have a body - the body is provided by the "implement"
class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces

Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
interface FirstInterface {
public void myMethod(); // interface method
}

interface SecondInterface {
public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

You might also like