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

Java Module 2

Module 2 covers inheritance, interfaces, and packages in Java, detailing types of inheritance such as single, hierarchical, multilevel, hybrid, and multiple inheritance. It explains member access rules, the use of the super keyword, method overriding, and the differences between abstract classes and interfaces. Additionally, it discusses defining, creating, accessing, and importing packages, along with access control within them.

Uploaded by

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

Java Module 2

Module 2 covers inheritance, interfaces, and packages in Java, detailing types of inheritance such as single, hierarchical, multilevel, hybrid, and multiple inheritance. It explains member access rules, the use of the super keyword, method overriding, and the differences between abstract classes and interfaces. Additionally, it discusses defining, creating, accessing, and importing packages, along with access control within them.

Uploaded by

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

MODULE-2:

INHERITANCE, INTERFACE AND PACKAGES


Inheritance basics, Types of inheritance, Member access rules, Usage of super key
word, Method overriding, Usage of final, Abstract classes, Interfaces - differences
between abstract classes and interfaces, defining an interface, implementing interface,
applying interfaces, variables in interface and extending interfaces; Packages -
defining, creating and accessing a package, importing packages, access control in
packages.

Inheritance:
A new class (called a subclass or child class) inherit the properties (fields) and
behaviors (methods) of an existing class (called a superclass or parent class) is called
inheritance.
Parent class: The class whose properties and behaviors inherited.
Child class: The class inherite the properties and behaviors from base class.

Use of Inheritance:
 Reuse code from the parent class.
 Code Reusability
 Extending Functionality
 Reducing Redundancy
 Supporting Dynamic Method Overriding
Syntax:
class parentclass{
//methods and fields;
}
Class childclass extends parentclass{
//methods and fields;
}

Types of inheritance:
1. Single Inheritance
2. Hierarchal Inheritance
3. Multilevel Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance
1. Single Inheritance: One class inherits from a single base class.

Example: Class A inherits from class B.

Example program for single inheritance:


// Base Class: Vehicle
class Vehicle {
String brand;
String colour;
String fuelType;
int speed;

void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Colour: " + colour);
System.out.println("Fuel Type: " + fuelType);
System.out.println("Speed: " + speed + " km/h");
}
}

// Child Class: Car


class Car extends Vehicle {
int wheels;

void displayCarInfo() {
displayInfo();
System.out.println("Wheels: " + wheels);
System.out.println("This car can carry 6 passengers.");
}
}

public class SingleInheritanceExample {


public static void main(String[] args) {
Car car = new Car();
car.brand = "Toyota";
car.colour = "Red";
car.fuelType = "Petrol";
car.speed = 120;
car.wheels = 4;

// Display car information


car.displayCarInfo();
}
}
Output:
Brand: Toyota
Colour: Red
Fuel Type: Petrol
Speed: 120 km/h
Wheels: 4
This car can carry 6 passengers.

2. Hierarchical Inheritance: Multiple classes inherit from a single base class.


Example: Class B, C and class D are inherit from class A.

Example Program for hierarchal Inheritance:


class Vehicle {
String brand;
String colour;
String fuelType;
int speed;

void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Colour: " + colour);
System.out.println("Fuel Type: " + fuelType);
System.out.println("Speed: " + speed + " km/h");
}
}

// Child Class 1: Car


class Car extends Vehicle {
int wheels;

void displayCarInfo() {
displayInfo();
System.out.println("Wheels: " + wheels);
System.out.println("This car can carry 6 passengers.");
}
}
// Child Class 2: Bike
class Bike extends Vehicle {
boolean hasHelmet;

void displayBikeInfo() {
displayInfo();
System.out.println("Has Helmet: " + hasHelmet);
System.out.println("This bike can carry 2 passengers.");
}
}

public class HierarchicalInheritanceExample {


public static void main(String[] args) {
// Creating an object of Car
Car car = new Car();
car.brand = "Honda";
car.colour = "Red";
car.fuelType = "Petrol";
car.speed = 150;
car.wheels = 4;
car.displayCarInfo();

// Creating an object of Bike


Bike bike = new Bike();
bike.brand = "Yamaha";
bike.colour = "Blue";
bike.fuelType = "Electric";
bike.speed = 100;
bike.hasHelmet = true;
bike.displayBikeInfo();
}
}
Output: Brand: Honda
Colour: Red
Fuel Type: Petrol
Speed: 150 km/h
Wheels: 4
This car can carry 6 passengers.
Brand: Yamaha
Colour: Blue
Fuel Type: Electric
Speed: 100 km/h
Has Helmet: true
This bike can carry 2 passengers.

3. Multilevel Inheritance: A class inherits from a derived class, which in turn inherits from
a base class.

Example: Class C inherits from class B, and class B inherits from class A.

Example program for multilevel inheritance.


// Base Class: Vehicle
class Vehicle {
String brand;
String colour;
String fuelType;
int speed;

void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Colour: " + colour);
System.out.println("Fuel Type: " + fuelType);
System.out.println("Speed: " + speed + " km/h");
}
}

// Intermediate Class: Car (inherits from Vehicle)


class Car extends Vehicle {
int wheels;

void displayCarInfo() {
displayInfo();
System.out.println("Wheels: " + wheels);
System.out.println("This car can carry 6 passengers.");
}
}

// Child Class: ElectricCar (inherits from Car)


class ElectricCar extends Car {
int batteryCapacity;

void displayElectricCarInfo() {
displayCarInfo();
System.out.println("Battery Capacity: " + batteryCapacity + " kWh");
System.out.println("This electric car can carry 4 passengers.");
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
ElectricCar eCar = new ElectricCar();
eCar.brand = "Tesla";
eCar.colour = "Black";
eCar.fuelType = "Electric";
eCar.speed = 200;
eCar.wheels = 4;
eCar.batteryCapacity = 75;

// Display ElectricCar information


eCar.displayElectricCarInfo();
}
}
Output:
Brand: Tesla
Colour: Black
Fuel Type: Electric
Speed: 200 km/h
Wheels: 4
This car can carry 6 passengers.
Battery Capacity: 75 kWh
This electric car can carry 4 passengers.

4. Hybrid Inheritance: A combination of different types of inheritance (such as multilevel


and hierarchical inheritance combined).

Example program for hybrid inheritance.


// Base Class: Vehicle
class Vehicle {
String brand;
String colour;
String fuelType;
int speed;

void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Colour: " + colour);
System.out.println("Fuel Type: " + fuelType);
System.out.println("Speed: " + speed + " km/h");
}

void displayPassengerCapacity(String vehicleType) {


if (vehicleType.equals("Car")) {
System.out.println("This car can carry 6 passengers.");
} else if (vehicleType.equals("Bike")) {
System.out.println("This bike can carry 2 passengers.");
} else if (vehicleType.equals("Bus")) {
System.out.println("This bus can carry 30 passengers.");
}
}
}

// Child Class 1: Car (inherits from Vehicle)


class Car extends Vehicle {
int wheels;

void displayCarInfo() {
displayInfo();
System.out.println("Wheels: " + wheels);
displayPassengerCapacity("Car");
}
}

// Child Class 2: ElectricCar (inherits from Car)


class ElectricCar extends Car {
int batteryCapacity; // specific to electric cars
void displayElectricCarInfo() {
displayCarInfo();
System.out.println("Battery Capacity: " + batteryCapacity + " kWh");
System.out.println("This electric car can carry 6 passengers.");
}
}

// Child Class 3: Bike (inherits from Vehicle)


class Bike extends Vehicle {
boolean hasHelmet;

void displayBikeInfo() {
displayInfo();
System.out.println("Has Helmet: " + hasHelmet);
displayPassengerCapacity("Bike");
}
}

// Child Class 4: Bus (inherits from Vehicle)


class Bus extends Vehicle {
int seatingCapacity;

void displayBusInfo() {
displayInfo();
System.out.println("Seating Capacity: " + seatingCapacity);
displayPassengerCapacity("Bus");
}
}

public class HybridInheritanceExample {


public static void main(String[] args) {
// Creating an object of Car
Car car = new Car();
car.brand = "Toyota";
car.colour = "Red";
car.fuelType = "Petrol";
car.speed = 120;
car.wheels = 4;
car.displayCarInfo();

// Creating an object of ElectricCar


ElectricCar electricCar = new ElectricCar();
electricCar.brand = "Tesla";
electricCar.colour = "White";
electricCar.fuelType = "Electric";
electricCar.speed = 150;
electricCar.wheels = 4;
electricCar.batteryCapacity = 75;
electricCar.displayElectricCarInfo();

// Creating an object of Bike


Bike bike = new Bike();
bike.brand = "Yamaha";
bike.colour = "Blue";
bike.fuelType = "Electric";
bike.speed = 80;
bike.hasHelmet = true;
bike.displayBikeInfo();

// Creating an object of Bus


Bus bus = new Bus();
bus.brand = "Mercedes";
bus.colour = "Yellow";
bus.fuelType = "Diesel";
bus.speed = 90;
bus.seatingCapacity = 30;
bus.displayBusInfo();
}
}

5. Multiple Inheritance (Java does not support multiple inheritance through classes,
but it can be achieved using interfaces):
 A class inherits from more than one base class (Java does not allow multiple
inheritance through classes to avoid ambiguity, but it allows multiple inheritance
through interfaces).

Member Access Rules:


To work with inheritance, different access specifiers control how members (variables
and methods) of a class are accessed in the child class (subclass). These access specifiers are:
 Public members are accessible anywhere, inside and outside the class.
 Private members are only accessible within the class where they are defined.
 Protected members are accessible inside the class, its subclasses, and classes in the
same package.
 Default (no specifier) members are accessible only within the same package.
Access Modifier Visibility Table
Access Modifier Same Class Same Package Subclasses Different Package
public Yes Yes Yes Yes
private Yes No No No
protected Yes Yes Yes No
default (no modifier) Yes Yes No No

Example:
class Vehicle {
public String brand;
private String fuelType; // Private member: can only be accessed within the Vehicle class
protected int speed; // Protected member: can be accessed by subclasses
int wheels; // Default access: can only be accessed within the same package

public Vehicle(String brand, String fuelType, int speed, int wheels) {


this.brand = brand;
this.fuelType = fuelType;
this.speed = speed;
this.wheels = wheels;
}
// Public method to access private members
public String getFuelType() {
return fuelType;
}
}
class Car extends Vehicle {
public Car(String brand, String fuelType, int speed, int wheels) {
super(brand, fuelType, speed, wheels); // Calling parent constructor
}
public void displayInfo() {
System.out.println("Car Brand: " + brand); // Public member (accessible directly)
System.out.println("Fuel Type: " + getFuelType()); // Private member accessed via public method
System.out.println("Car Speed: " + speed); // Protected member (accessible in subclass)
System.out.println("Car Wheels: " + wheels); // Default access (works within same package)
}
}
class Bike extends Vehicle {
public Bike(String brand, String fuelType, int speed, int wheels) {
super(brand, fuelType, speed, wheels); // Calling parent constructor
}
public void displayInfo() {
System.out.println("Bike Brand: " + brand); // Public member (accessible directly)
System.out.println("Fuel Type: " + getFuelType()); // Private member accessed via public method
System.out.println("Bike Speed: " + speed); // Protected member (accessible in subclass)
System.out.println("Bike Wheels: " + wheels); // Default access (works within same package)
}
}

public class TestInheritance {


public static void main(String[] args) {
// Create instances of Car and Bike
Car car = new Car("Toyota", "Petrol", 150, 4);
car.displayInfo(); // Display car details

Bike bike = new Bike("Yamaha", "Electric", 80, 2);


bike.displayInfo(); // Display bike details
}
}
Modifier Accessibility Exam Behavior
public Can be accessed anywhere, brand in Vehicle is directly accessible
inside and outside the class. from Car and Bike.
private Can only be accessed within fuelType is accessed in Car and Bike via
the same class where it is getFuelType() method.
defined.
protected Can be accessed within the speed is directly accessible in Car and
class, by subclasses, and by Bike since they are subclasses of Vehicle.
classes in the same package.
default Can be accessed only within wheels is accessible because Car and Bike
the same package. are in the same package as Vehicle.

super keyword:
The super keyword in Java is used to refer to the superclass (parent class) of the current
object. It can be used in a few contexts:
1. Accessing Superclass Fields: You can use super to access fields of the superclass if
the subclass has a field with the same name.
2. Accessing Superclass Methods: When a subclass overrides a method, you can use
super to call the method from the superclass.
3. Accessing Superclass Constructor: It can be used to call a constructor of the
superclass from the subclass constructor.
1. super can be used to refer immediate parent class instance variable
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
Example:
class Vehicle {
String brand = "Toyota"; // Parent class instance variable
}
class Car extends Vehicle {
String brand = "Honda"; // Child class instance variable
void display() {
System.out.println("Car Brand: " + brand); // Display the child's own brand
System.out.println("Vehicle Brand: " + super.brand); // Access the parent class's brand using super
}
}
public class TestSuper {
public static void main(String[] args) {
Car car = new Car();
car.display();
}
}
Output:
Car Brand: Honda
Vehicle Brand: Toyota
To access the brand from the Vehicle class (parent), we use super.brand.

2. super can be used to invoke immediate parent class method


super.method(): Used to call the method from the parent class when it’s overridden in the
child class (if child class contains the same method as parent class).
Example:
class Vehicle {
void start() {
System.out.println("Vehicle is starting...");
}
}
class Car extends Vehicle {
void start() {
System.out.println("Car is starting...");
}
void display() {
super.start();// Call the start method of the parent class (Vehicle)
start();// Call the start method of the child class (Car)
}
}
public class TestSuper {
public static void main(String[] args) {
Car car = new Car();
car.display();
}
}
Output:
Vehicle is starting...
Car is starting...

Inside the display() method, super.start() calls the start() method of the Vehicle class,
while just calling start() invokes the start() method from the Car class.

3. super() can be used to invoke immediate parent class constructor:


super(): Calls the parent class's constructor from the child class, usually to ensure proper
initialization in the inheritance hierarchy.

Example:
class Vehicle {
Vehicle(String brand) {
System.out.println("Vehicle Brand: " + brand);
}
}
class Car extends Vehicle {
Car() {
super("Toyota");// Call the constructor of the parent class using super()
System.out.println("Car is ready!");
}
}
public class TestSuper {
public static void main(String[] args) {
Car car = new Car();
}
}
Output:
Vehicle Brand: Toyota
Car is ready!
The Car class has a constructor that calls the parent class constructor using
super("Toyota") to pass the brand value to the Vehicle class constructor.

Polymorphism:
Polymorphism in Java is the ability of an object to take many forms. It means that you
can use the same method or class in different ways, depending on the context.
There are two types of polymorphism:
1. Method Overloading (Compile-time Polymorphism):
o When you have multiple methods with the same name but different
parameters.
o The method to be called is determined at compile time.
2. Method Overriding (Runtime Polymorphism):
o When a subclass provides its own implementation of a method that is already
defined in the superclass.
o The method to be called is determined at runtime based on the object type.

Method Overriding:
The primary purpose of method overriding is to allow the subclass to provide a specific
behavior for a method that is already defined in the superclass, essentially "overriding" the
inherited behavior.
Key Points:
1. Same method signature: The method in the subclass must have the same method
signature (name, parameters, return type) as the method in the superclass.
2. Runtime polymorphism: Method overriding is a type of runtime polymorphism
(also known as dynamic method dispatch). The method that gets called is determined
at runtime, based on the object type, not the reference type.
3. Inheritance: The subclass must inherit from the superclass in order to override a
method.
4. Access Modifiers: The overridden method in the subclass cannot have a more
restrictive access modifier than the method in the superclass. For example, if the
superclass method is public, the subclass method must also be public (or more
permissive, like protected).
Syntax:
class Superclass {
// Method in the superclass
returnType methodName(parameters) {
// method body
}
}
class Subclass extends Superclass {
// Overriding the method in the subclass
@Override
returnType methodName(parameters) {
// subclass specific implementation
}
}

Example:
class Employee {
double baseSalary = 50000;
void calculateSalary() {
System.out.println("Calculating salary for a general employee...");
}
}
class Manager extends Employee {
void calculateSalary() {// Overriding the calculateSalary method in Manager class
double bonus = 20000;
double totalSalary = baseSalary + bonus;
System.out.println("Manager's Salary with bonus: " + totalSalary);
}
}
class Engineer extends Employee {
void calculateSalary() {// Overriding the calculateSalary method in Engineer class
double bonus = 10000;
double totalSalary = baseSalary + bonus;
System.out.println("Engineer's Salary with bonus: " + totalSalary);
}
}
public class Test {
public static void main(String[] args) {
Employee emp1 = new Manager(); // Reference to Employee but object is Manager
Employee emp2 = new Engineer(); // Reference to Employee but object is Engineer
emp1.calculateSalary(); // Calls Manager's overridden method
emp2.calculateSalary(); // Calls Engineer's overridden method
}
}

Output:
Manager's Salary with bonus: 70000.0
Engineer's Salary with bonus: 60000.0
Differences between Method Overloading and Method Overriding

Method Overloading Method Overriding


It is performed within a class. It is performed between two classes that have
inheritance relationship.
Signature must be different. Signature must be the same.
It is example of compile time polymorphism. It is example of run time polymorphism.
It is used to increase readability of program. It is used to provide different implementation of
super class method.
Static methods can be overloaded. Static methods can’t be override.
Private methods can be overloaded. Private methods can’t be override.
Final methods can be overloaded. Final methods can’t be override.
Return type of method may be same or different. Return type must be the same.

final keyword:
The final keyword is used to define constants, prevent method overriding, and prevent
class inheritance. It is a way to "restrict" certain features of a class, method, or variable.
Final Variable: Once assigned, the value cannot be changed.
Final Method: The method cannot be overridden by subclasses.
Final Class: The class cannot be inherited.
1. Final Variable:
When you declare a variable as final, its value cannot be changed once it is initialized.
Essentially, it becomes a constant.
Syntax:
final dataType variableName = value;
Example:
class Sample {
final int a = 10;

Sample() {
a = 20; // Error: cannot assign a value to final variable
}
}

class Test {
public static void main(String args[]) {
Sample obj = new Sample();
}
}
Explanation: In this case, a is declared as a final variable. In the constructor, we attempt to
change its value, but since it's a final variable, this results in a compilation error. Once a final
variable is assigned a value, it cannot be changed.
2. Final Method
When a method is declared as final, it cannot be overridden by any subclass. This is useful
when you want to ensure that a method’s behavior is preserved in subclasses.
Syntax:
final returnType methodName() {
// method body
}
Example:
class Base {
final void show() {
System.out.println("show() in Base Class");
}
}

class Derived extends Base {


void show() { // Error: cannot override final method
// System.out.println("show() in Derived Class");
}
}

public class Test {


public static void main(String args[]) {
Derived obj = new Derived();
obj.show(); // This will call the Base class show() method
}
}
Explanation: The show() method in the Base class is declared as final, so in the Derived class,
trying to override it results in a compilation error. This ensures that the method’s
implementation in Base remains unchanged in Derived.
3. Final Class
When a class is declared as final, it cannot be subclassed. This is useful when you
want to prevent inheritance.
Syntax:
final class ClassName {
// class body
}
Example:
final class Base {
void show() {
System.out.println("show() in Base");
}
}

class Derived extends Base { // Error: cannot subclass final class


void show() {
System.out.println("Show() in Derived");
}
}

public class Test {


public static void main(String args[]) {
Derived obj = new Derived();
}
}
Explanation: The class Base is declared as final, so it cannot be extended (inherited).
Attempting to create a Derived class that extends Base will result in a compilation error.

Abstract Class:
An abstract class in Java is a class that cannot be instantiated directly. It is meant to
be subclassed by other classes. Abstract classes can contain both abstract methods (methods
without implementation) and concrete methods (methods with implementation). Abstract
methods must be implemented by subclasses, but concrete methods can be inherited as-is or
overridden.
Key Points About Abstract Classes in Java:
1. Abstract class cannot be instantiated.
2. It can contain abstract methods (methods without implementation).
3. It can also contain concrete methods (methods with implementation).
4. A subclass of an abstract class must implement all the abstract methods, or it must be
declared abstract itself.
Syntax for Abstract Class in Java:
abstract class abstractClassname {
abstract void abstractMethod();// Abstract method (no implementation)
}
Class childclass extends abstractclassname{
void concreteMethod() {// Concrete method (with implementation)
System.out.println("This is a concrete method.");
}
How to Define an Abstract Class:
1. Use the abstract keyword before the class declaration.
2. Declare abstract methods (methods without body) using the abstract keyword.
3. Optionally, you can include concrete methods that have a method body.
Example:
abstract class PaymentMethod {
// Abstract method (must be implemented by subclasses)
abstract void processPayment(double amount);
}

class CreditCardPayment extends PaymentMethod {


void processPayment(double amount) {
System.out.println("Processing credit card payment of " + amount);
}
}

class PayPalPayment extends PaymentMethod {


void processPayment(double amount) {
System.out.println("Processing PayPal payment of " + amount);
}
}

class DebitCardPayment extends PaymentMethod {


void processPayment(double amount) {
System.out.println("Processing debit card payment of " + amount);
}
}

public class Main {


public static void main(String[] args) {
PaymentMethod payment1 = new CreditCardPayment();
payment1.processPayment(100.50); // Output: Processing credit card payment of 100.5

PaymentMethod payment2 = new PayPalPayment();


payment2.processPayment(75.25); // Output: Processing PayPal payment of 75.25
PaymentMethod payment3 = new DebitCardPayment();
payment3.processPayment(50.0); // Output: Processing debit card payment of 50.0
}
}
Output:
Processing credit card payment of 100.5
Processing PayPal payment of 75.25
Processing debit card payment of 50.0

Interface:
An interface is a blueprint for a class in programming. It defines a contract of methods
(without implementation) that a class must implement. An interface only specifies what
methods a class should have, but not how they should be implemented.
Conditions for Using an Interface:
1. No Implementation: Methods in an interface are abstract by default (i.e., no method
body).
2. Multiple Implementation: A class can implement multiple interfaces, providing
flexibility in design.
3. Access Modifiers: Methods in an interface are public by default. You cannot have
private or protected methods in an interface.
4. Variables in Interfaces: Any variables defined in an interface are implicitly public,
static, and final (constants). They must be initialized when declared.
5. Interface Inheritance: An interface can extend another interface, allowing it to inherit
abstract methods from the parent interface.

1. Syntax of an Interface
In Java, the syntax for defining an interface looks like this:
interface InterfaceName {
// abstract methods (methods without implementation)
returnType methodName1(parameterList);
returnType methodName2(parameterList);
}
 InterfaceName: Name of the interface.
 Abstract Methods: These methods are declared without bodies, i.e., no
implementation is provided in the interface itself.
2. Defining an Interface
To define an interface in Java, we use the interface keyword. For example, let's consider an
interface for a vehicle:
interface Vehicle {
// Abstract method
void start();
void stop();
}
Here, the Vehicle interface declares two abstract methods, start() and stop(), without defining
how these methods work.
3. Implementing an Interface
To use the interface, a class must implement it. The implements keyword is used to indicate
that a class is implementing an interface. It is mandatory for the implementing class to
provide concrete implementations for all abstract methods defined in the interface.
For example:
class Car implements Vehicle {
// Providing implementation of start() method
public void start() {
System.out.println("Car is starting");
}

// Providing implementation of stop() method


public void stop() {
System.out.println("Car is stopping");
}
}
In this example, the Car class implements the Vehicle interface, and it provides concrete
implementations of the start() and stop() methods.
4. Applying Interfaces (Using an Interface)
Once a class implements an interface, you can create objects of that class and invoke
the methods defined in the interface.
Example:
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car(); // Creating a Car object, using Vehicle reference
myCar.start(); // Calls the start method from the Car class
myCar.stop(); // Calls the stop method from the Car class
}
}
Here, even though myCar is a reference of type Vehicle, it is pointing to an object of the Car
class, and it can invoke the start() and stop() methods because Car implements the Vehicle
interface.
5. Variables in Interfaces
In an interface, you can define constants (i.e., variables), but they must be public,
static, and final by default. Since they are constants, they cannot be modified after
initialization.
Example:
interface Vehicle {
// Constant variable
int MAX_SPEED = 120; // By default public, static, final
void start();
void stop();
}
In the above code, MAX_SPEED is a constant that will be used by classes implementing the
Vehicle interface.

Interface Extending Concept:


This concept is similar to class inheritance, but it allows for multiple inheritance of
behavior, as interfaces can extend multiple other interfaces.
Let's consider an example of vehicles:
We have two main behaviors that vehicles can have: one is related to driving and the other to
fueling. These behaviors are common to many vehicles.
o Drivable vehicles: Cars, Bikes, Trucks, etc.
o Fuelable vehicles: Cars, Trucks, etc. (both require fueling to operate).
We can represent these behaviors using two interfaces: Drivable and Fuelable. And then we
can create another interface Vehicle that extends both of these interfaces, combining the
behaviors for a complete vehicle.
1. Defining the Interfaces:
// Drivable Interface
interface Drivable {
void drive(); // Method for driving behavior
}

// Fuelable Interface
interface Fuelable {
void fuelUp(); // Method for fueling behavior
}
In this example, both Drivable and Fuelable interfaces have one method each (drive() and
fuelUp(), respectively).
2. Extending the Interfaces:
Now, let's create a Vehicle interface that extends both the Drivable and Fuelable interfaces.
This interface combines the functionality of both interfaces, and any class that implements
Vehicle must provide implementations for both drive() and fuelUp() methods.
// Vehicle Interface extending both Drivable and Fuelable interfaces
interface Vehicle extends Drivable, Fuelable {
void startEngine(); // Additional method specific to vehicles
}
Now, the Vehicle interface has inherited both the drive() method from Drivable and the
fuelUp() method from Fuelable, and it also adds its own method startEngine().
3. Implementing the Extended Interface:
Let’s implement the Vehicle interface in a class, say, for a Car:
class Car implements Vehicle {
public void drive() {
System.out.println("The car is driving.");
}

public void fuelUp() {


System.out.println("Filling the car with fuel.");
}

public void startEngine() {


System.out.println("Starting the car's engine.");
}
}
In this class Car, we’ve implemented the methods drive(), fuelUp(), and startEngine(). The
class Car is now a complete vehicle because it implements all the behaviors defined in the
Vehicle interface, which extends both Drivable and Fuelable.
4. Using the Interface in Code:
Now, let’s create an object of the Car class and use the methods from the interface:
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car(); // Vehicle reference, Car object
myCar.startEngine(); // Calls the startEngine method from Car
myCar.drive(); // Calls the drive method from Car
myCar.fuelUp(); // Calls the fuelUp method from Car
}
}

Difference between abstract and interface:


Feature Abstract Class Interface
Purpose Suitable when sharing Suitable when defining a
common functionality/state. contract that multiple classes can
follow.
Methods Can have both abstract and Can have abstract methods,
concrete methods. default methods, and static
methods (since Java 8).
Variables Can have instance variables All fields are public, static, and
with any access modifiers. final (constants).
Inheritance Supports single inheritance Supports multiple inheritance
(extends one abstract class). (implements multiple interfaces).
Constructor Can have constructors. Cannot have constructors.
Method Can provide concrete Can provide default methods
Implementation methods with (optional to override).
implementation.
Extends/Implements A class extends one abstract A class implements one or more
class. interfaces.
Instantiation Cannot be instantiated Cannot be instantiated directly.
directly (must be extended).
Keyword Defined using the abstract Defined using the interface
keyword. keyword.

Packages in Java
A package in Java is a namespace used to group related classes, interfaces, and sub-
packages. It is used to organize the code in a hierarchical structure, making it easier to manage
large codebases, avoid name conflicts, and control access. A package is a way of grouping
related classes and interfaces together.
Packages are essential for:
1. Code organization – They group related classes into namespaces, which makes the
code easy to manage.
2. Access control – Packages provide access protection using access modifiers.
3. Avoiding name conflicts – Classes with the same name can exist in different
packages without conflict.
4. Reusability – Code in one package can be reused by importing it into other programs.
Types of Packages
1. Built-in Packages: These are pre-defined packages provided by the Java API (e.g.,
java.util, java.io).
2. User-defined Packages: These are custom packages created by the user to organize
their code.
Syntax for Defining a Package
To define a package in Java, you use the package keyword at the top of your Java source file.
Here's the syntax:
package package_name;
Access Control in Packages
Java provides access control mechanisms that determine which classes, methods, and fields
are accessible. These are controlled using access modifiers:
1. public: The class, method, or field is accessible from any other class.
2. protected: The method or field is accessible within the same package and by
subclasses.
3. private: The method or field is only accessible within the same class.
4. Default (no modifier): The method or field is accessible only within classes in the
same package.

Packages in Java working in Eclipse softawre:


In Java, packages are used to group related classes and interfaces together. They help
organize code, making it more modular and easier to manage. Packages also help avoid name
conflicts by differentiating classes with the same name when they belong to different packages.
Example in Eclipse: Creating Packages and Accessing Methods
Here’s a step-by-step guide on how to create packages, classes, and access methods from
different packages in Eclipse:
Step 1: Create a New Java Project
1. Open Eclipse and navigate to File > New > Java Project.
2. Name your project (e.g., PackageExample).
3. Click Finish.

Step 2: Create Packages in Eclipse


1. Right-click on the src folder in the Package Explorer.
2. Select New > Package.
3. Name your package (e.g., com.example.model for a model package,
com.example.service for a service package).
4. Click Finish.
Repeat these steps to create multiple packages for better organization.

Step 3: Create Classes inside Packages


1. Right-click on the newly created package (e.g., com.example.model).
2. Select New > Class.
3. Name the class (e.g., Employee).
4. If needed, check the box for public static void main(String[] args) to create a main
method for testing.
5. Click Finish.
Repeat the process for other classes in different packages (e.g., create a Manager class in
com.example.service).
Step 4: Write Code in the Classes
Let’s create two packages:
1. com.example.model: Contains an Employee class.
2. com.example.service: Contains a Manager class that interacts with Employee.
1. Create Employee Class in com.example.model:
// com/example/model/Employee.java
package com.example.model;
public class Employee {
private String name;
private double salary;
// Constructor
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
// Getter for name
public String getName() {
return name;
}
// Getter for salary
public double getSalary() {
return salary;
}
// Method to display employee details
public void displayDetails() {
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: " + salary);
}
}
2. Create Manager Class in com.example.service:
// com/example/service/Manager.java
package com.example.service;
import com.example.model.Employee; // Importing the Employee class from model package
public class Manager {
private Employee employee;
// Constructor that accepts an Employee object
public Manager(Employee employee) {
this.employee = employee;
}
// Method to access Employee's details
public void printEmployeeDetails() {
System.out.println("Manager is managing the following employee:");
employee.displayDetails();
}
}
3. Create Main Class in com.example.main:
// com/example/main/Main.java
package com.example.main;
import com.example.model.Employee; // Importing Employee from model package
import com.example.service.Manager; // Importing Manager from service package
public class Main {
public static void main(String[] args) {
// Create an Employee object
Employee emp = new Employee("John Doe", 50000);
// Create a Manager object and pass the Employee object to it
Manager mgr = new Manager(emp);

// Manager accesses Employee's details through the method


mgr.printEmployeeDetails();
}
}

Step 5: Run the Program in Eclipse


1. Right-click on Main.java in the com.example.main package.
2. Select Run As > Java Application.
Expected Output:
Manager is managing the following employee:
Employee Name: John Doe
Employee Salary: 50000.0

Packages in Java working in Visual Studio Code softawre:


Here’s a step-by-step guide on how to work with packages in Java using Visual
Studio Code (VS Code), a popular and lightweight IDE for Java development.
Prerequisites:
1. Java Development Kit (JDK) should be installed on your system.
2. Visual Studio Code should be installed.
3. Java Extension Pack installed in Visual Studio Code (it provides all the necessary
extensions for Java development).
Steps for Working with Packages in Java in Visual Studio Code:
Step 1: Install Visual Studio Code & Java Extensions
1. Install Visual Studio Code:
o Download Visual Studio Code from here and install it.
2. Install Java Extensions:
o Launch VS Code and go to the Extensions view by clicking on the
Extensions icon on the left sidebar (or press Ctrl+Shift+X).
o Search for Java Extension Pack and install it. This includes extensions for
Java language support, debugging, Maven/Gradle, etc.
o You might also want to install Java Dependency Viewer to visualize the
project structure.
Step 2: Set Up Your Java Project
1. Create a Project Folder:
o Create a folder for your Java project (e.g., JavaPackagesExample).
o Open the folder in Visual Studio Code by clicking on File > Open Folder.
2. Initialize a New Java Project:
o Inside Visual Studio Code, open the Command Palette (Ctrl+Shift+P).
o Type and select Java: Create Java Project.
o Choose No Build Tools (or you can select Maven/Gradle if you want).
o Choose a folder to create your Java project in.
o It will create a src folder where your Java classes will go.
Step 3: Create and Use Packages
1. Create Packages:
o Inside the src folder, create subfolders for your packages:
o The folder structure should look like this:
2. Create Classes in the Packages:
o Inside the package, create a class file (ex: Circle.java).
3. Open Class file and write the Code:
o Circle.java (inside shapes package):
4. Create the Main Program:
o Create a file Main.java inside the src folder (not inside a package).
o This will serve as the entry point to the program.
o Main.java:
Step 4: Compile and Run the Program
1. Open Integrated Terminal:
o Open the Terminal in Visual Studio Code (Ctrl+ or from the top menu
Terminal > New Terminal).
2. Compile the Java Classes:
o In the terminal, navigate to the src directory using the command cd src.
o Now compile the Java classes using the following command:
Example; javac shapes/Circle.java geometry/AreaCalculator.java Main.java
o This will generate the .class files for each Java file.
3. Run the Program:
o After compiling, you can run the program using the java command:
java Main
Step 5: Use Visual Studio Code Features
 Running and Debugging: You can run and debug your program directly from Visual
Studio Code using the built-in Java extension.
o Click the green play icon (Run) or use F5 to start debugging.
 Package Structure Visualization: You can use the Java Dependency Viewer to see
the structure of your project and how packages are organized.

Example: library management system that consists of multiple modules, such as a book
management module, user management, and payment management. You can organize
these modules into different packages for better code structure.
Directory Structure:
library-management/
├── books/
| Book.java
| BookManager.java
├── users/
| User.java
| UserManager.java
├── payment/
| Payment.java
| PaymentProcessor.java
└── Main.java
Book.java (inside the books package):
package books;
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
}
BookManager.java (inside the books package):
package books;
import users.User;
public class BookManager {
public void lendBook(Book book, User user) {
System.out.println(user.getName() + " has borrowed the book: " + book.getTitle());
}
}
User.java (inside the users package):
package users;
public class User {
private String name;
public User(String name) {
this.name = name;
}

public String getName() {


return name;
}
}
Main.java (entry point):
import books.Book;
import books.BookManager;
import users.User;
public class Main {
public static void main(String[] args) {
User user = new User("John Doe");
Book book = new Book("Java Programming", "Jane Smith");
BookManager manager = new BookManager();
manager.lendBook(book, user);
}
}
Output:
John Doe has borrowed the book: Java Programming
Key Takeaways
 Defining a Package: Use package package_name; at the top of your Java file.
 Creating a Package: Organize classes in directories corresponding to the package
structure.
 Importing Packages: Use import to access classes from other packages.
 Access Control: Use access modifiers (public, private, protected, default) to control
the visibility and accessibility of classes, methods, and fields.

You might also like