Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

JAVA-Notes-Unit-2_Part 2

This document covers key concepts of Interfaces and Packages in Java, including the definition, features, and implementation of interfaces, as well as the creation and usage of packages. It highlights the differences between abstract classes and interfaces, and explains multiple inheritance through interfaces. Additionally, it provides examples of built-in and user-defined packages, emphasizing the importance of organization, name conflict avoidance, and access control in Java programming.

Uploaded by

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

JAVA-Notes-Unit-2_Part 2

This document covers key concepts of Interfaces and Packages in Java, including the definition, features, and implementation of interfaces, as well as the creation and usage of packages. It highlights the differences between abstract classes and interfaces, and explains multiple inheritance through interfaces. Additionally, it provides examples of built-in and user-defined packages, emphasizing the importance of organization, name conflict avoidance, and access control in Java programming.

Uploaded by

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

OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Interfaces and Packages


Interfaces: Introduction to Interfaces, differences between abstract classes and
interfaces, multiple inheritance through interfaces,
Packages: Creating and accessing a package, Understanding CLASSPATH, importing
packages.
Interfaces
Interfaces in Java are a collection of abstract and public methods we want our classes
to implement. It is the blueprint of a class and contains static constants and abstract
methods. Interfaces are fully unimplemented one.

Interfaces are used to achieve abstraction and implement multiple inheritance.

Syntax of Interface

interface InterfaceName
{
void method1(); // Abstract method (no body)
// Default method with implementation
default void method2()
{
System.out.println("This is a default method in the interface.");
}
// Static method with implementation
static void method3()
{
System.out.println("This is a static method in the interface.");
}
}

Key Features of Interfaces:

1. Abstract Methods: All methods in an interface are implicitly abstract (unless


they are default or static methods).
2. No Method Body: An interface only defines method signatures; it does not
provide method implementations (except for default and static methods).
3. Multiple Inheritance: A class can implement multiple interfaces, which allows
for multiple inheritance of behavior.

B.Tech (CSE-DS)-II-II Sem Page 1


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

4. Implementing Interfaces: A class that implements an interface must provide


concrete implementations for all of the interface’s abstract methods (unless the
class is abstract).
5. default and static Methods: Since Java 8, interfaces can contain default
methods with an implementation, as well as static methods.

Relationship Between Classes and Interfaces

As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

Important Points about interfaces

 We can’t create an instance (interface can’t be instantiated) of the interface but we


can make the reference of it that refers to the Object of its implementing class.
 A class can implement more than one interface.
 An interface can extend to another interface or interface (more than one interface).
 A class that implements the interface must implement all the methods in the
interface.
 All the methods are public and abstract. All the fields are public, static, and final.
 It is used to achieve multiple inheritances.
 Inside the Interface not possible to declare instance variables because by default
variables are public static final.
 Inside the Interface, constructors are not allowed.
 Inside the interface main method is not allowed.
 Inside the interface, static, final, and private methods declaration are not possible.

B.Tech (CSE-DS)-II-II Sem Page 2


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//Program to implement interfaces


// Interface: Vehicle
interface Vehicle
{
// Abstract methods (no body)
void start();
void stop();
void accelerate();
void honk();
}

// Class Car implementing the Vehicle interface


class Car implements Vehicle
{
private String brand;
private String model;
// Constructor
public Car(String brand, String model)
{
this.brand = brand;
this.model = model;
}
// Implementing the start method from the Vehicle interface
public void start()
{
System.out.println(brand + " " + model + " is starting.");
}
// Implementing the stop method from the Vehicle interface
public void stop()
{
System.out.println(brand + " " + model + " is stopping.");
}
// Implementing the accelerate method from the Vehicle interface
public void accelerate()
{
System.out.println(brand + " " + model + " is accelerating.");
}

B.Tech (CSE-DS)-II-II Sem Page 3


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Implementing the honk method from the Vehicle interface


public void honk()
{
System.out.println(brand + " " + model + " is honking: Beep Beep!");
}
}
// Class Truck implementing the Vehicle interface
class Truck implements Vehicle
{
private String brand;
private String model;
public Truck(String brand, String model)
{
this.brand = brand;
this.model = model;
}
// Implementing the start method from the Vehicle interface
public void start()
{
System.out.println(brand + " " + model + " truck is starting.");
}
// Implementing the stop method from the Vehicle interface
public void stop()
{
System.out.println(brand + " " + model + " truck is stopping.");
}
// Implementing the accelerate method from the Vehicle interface
public void accelerate()
{
System.out.println(brand + " " + model + " truck is accelerating.");
}
// Implementing the honk method from the Vehicle interface
public void honk()
{
System.out.println(brand + " " + model + " truck is honking: Horn Horn!");
}
}

B.Tech (CSE-DS)-II-II Sem Page 4


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Main class to demonstrate the usage of Vehicle interface


public class InterfaceEx
{
public static void main(String[] args)
{
// Create objects of Car and Truck
Vehicle c = new Car("Toyota", "Camry");
Vehicle t = new Truck("Ford", "F-150");

// Demonstrate using the interface methods


System.out.println("Car Actions:");
c.start();
c.accelerate();
c.honk();
c.stop();

System.out.println("\nTruck Actions:");
t.start();
t.accelerate();
t.honk();
t.stop();
}
}

B.Tech (CSE-DS)-II-II Sem Page 5


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Differences between abstract classes and interfaces

S.No Abstract class Interface

The abstract keyword is used to The interface keyword is used to


1.
declare abstract class. declare interface.

It has partially implemented and


2. It has fully unimplemented methods
partially unimplemented methods

Interface can have only abstract


Abstract class can have abstract and methods.
3.
non-abstract methods. Since Java 8, it can have default and
static methods also.

An abstract class can be extended An interface can be implemented


4.
using keyword "extends". using keyword "implements".

An abstract class can have class Members of interface are public by


5.
members like private, protected, etc. default.

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

7. Abstract Class can have constructors Interface cannot have constructors

Abstract class can provide the Interface can't provide the


8.
implementation of interface. implementation of abstract class.

An abstract class can extend another An interface can extend another


9. Java class and implement multiple Java interface or multiple interfaces
Java interfaces. only.

Abstract class doesn't support Interface supports multiple


10.
multiple inheritance. inheritance.

Example: Example:
public abstract class Shape public interface Drawable
11. { {
public abstract void draw(); void draw();
} }

B.Tech (CSE-DS)-II-II Sem Page 6


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Multiple Inheritance through interfaces


In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes. Please note that Java
does not support multiple inheritances with classes. In Java, we can achieve multiple
inheritances only through Interfaces. In the image below, Class C is derived from
interfaces A and B.

//Program to implement Multiple Inheritance through interfaces

// Interface for Engine-related behavior


interface Engine
{
void startEngine(); // Abstract method to start the engine
void stopEngine(); // Abstract method to stop the engine
}

// Interface for general vehicle behavior


interface Vehicle
{
void drive(); // Abstract method for driving the vehicle
void honk(); // Abstract method for honking the vehicle
}

B.Tech (CSE-DS)-II-II Sem Page 7


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Car class that implements both Engine and Vehicle interfaces


class Car implements Engine, Vehicle
{
private String brand;
private String model;

// Constructor to initialize the car's brand and model


public Car(String brand, String model)
{
this.brand = brand;
this.model = model;
}

// Implementing startEngine from Engine interface


public void startEngine()
{
System.out.println(brand + " " + model + " engine started.");
}

// Implementing stopEngine from Engine interface


public void stopEngine()
{
System.out.println(brand + " " + model + " engine stopped.");
}

// Implementing drive from Vehicle interface


public void drive()
{
System.out.println(brand + " " + model + " is driving.");
}

// Implementing honk from Vehicle interface


public void honk()
{
System.out.println(brand + " " + model + " is honking: Beep Beep!");
}
}

B.Tech (CSE-DS)-II-II Sem Page 8


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

// Main class to demonstrate multiple inheritance through interfaces


public class Multiple
{
public static void main(String[] args)
{
// Create an object of Car which implements both Engine and Vehicle interfaces
Car c = new Car("Toyota", "Camry");
// Use the methods from both Engine and Vehicle interfaces
c.startEngine(); // Engine-related behavior
c.drive(); // Vehicle-related behavior
c.honk(); // Vehicle-related behavior
c.stopEngine(); // Engine-related behavior
}
}

Packages
Creating and accessing a package
In Java, packages are used to group related classes and interfaces together. This
helps in organizing code in a logical manner and avoiding name conflicts. A package
also controls access to classes and members, helping with encapsulation.

Types of Packages:

1. Built-in Packages: These are provided by the Java API (e.g., java.util, java.io,
java.lang). They come pre-installed with the Java Development Kit (JDK).
2. User-defined Packages: These are packages that you define for your own
classes and interfaces.

B.Tech (CSE-DS)-II-II Sem Page 9


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Importance of Packages?

1. Organization: Packages allow you to logically group related classes and interfaces,
making it easier to maintain and manage code.
2. Name Conflict Avoidance: By placing classes in different packages, you can avoid
name conflicts between classes with the same name.
3. Access Control: Packages provide a way to control access to classes, methods, and
variables using access modifiers like private, protected, and public.
4. Reusability: Packages allow code to be reused across different projects by creating
modular and organized libraries.

Syntax for Declaring a Package

At the top of a Java source file, you can declare the package it belongs to using the
package keyword:

package package_name;

Ex:

package com.mahindra.utility;
public class Vehicle
{
// class implementation
}

1. Built-In Packages

In Java, built-in packages are predefined and included in the Java Standard
Library (Java API). These packages provide a wide range of functionality that can be
used directly in your programs without having to write the code yourself.

The Java standard library contains packages that allow you to work with data
structures, file handling, networking, utilities, and more.

B.Tech (CSE-DS)-II-II Sem Page 10


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Here are some of the most commonly used built-in packages in Java:

1. java.lang Package
 Description: This is one of the most fundamental packages in Java. It is
automatically imported in every Java program, so you don’t need to explicitly
import it.
 Classes and Interfaces:
o String: Represents strings of characters.
o Math: Provides mathematical functions like sqrt(), pow(), etc.
o Object: The root class of the Java class hierarchy.
o System: Provides system-related utility methods (e.g.,
System.out.println() ).
o Thread: Represents a thread of execution.
o Exception, RuntimeException: Represents exceptions in Java.

2. java.util Package
 Description: Provides classes and interfaces for data structures, date and time,
and utility classes.
 Classes and Interfaces:

o ArrayList: A resizable array implementation of the List interface.


o HashMap: Implements the Map interface, storing key-value pairs.
o Date: Represents date and time.
o Collections: Contains static methods for manipulating collections (e.g.,
sorting, reversing).
o Scanner: Used to get input from the user.

3. java.io Package
 Description: Contains classes and interfaces for input and output (I/O)
operations like reading from or writing to files, and working with data streams.
 Classes and Interfaces:

o File: Represents a file or directory path.


o FileReader, BufferedReader: Used for reading data from files.
o FileWriter, BufferedWriter: Used for writing data to files.
o InputStream, OutputStream: For byte-based I/O.
o ObjectInputStream, ObjectOutputStream: For object serialization.

B.Tech (CSE-DS)-II-II Sem Page 11


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

4. java.net Package

 Description: Provides classes for networking operations such as sending and


receiving data over the network.
 Classes and Interfaces:
o Socket: Used for creating client-side TCP connections.
o ServerSocket: Used for creating server-side TCP connections.
o URL: Represents a Uniform Resource Locator (URL).
o URLConnection: Provides methods for communicating with URLs.

5. java.sql Package

 Description: Provides classes and interfaces for working with databases using
JDBC (Java Database Connectivity).
 Classes and Interfaces:
o Connection: Represents a connection to a database.
o Statement: Used to execute SQL queries.
o ResultSet: Represents the result set of a query.
o DriverManager: Manages database drivers.

6. java.awt Package

 Description: The java.awt (Abstract Window Toolkit) package is part of Java's


Java Foundation Classes (JFC) and provides a set of APIs for building
Graphical User Interfaces (GUIs) in Java.
 It contains classes for building windows, buttons, text fields, layouts, and other
graphical components that can be used in Java desktop applications.

B.Tech (CSE-DS)-II-II Sem Page 12


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

//Program to implement Built-in Packages

import java.lang.*;
import java.util.ArrayList;
import java.io.*;
import java.io.IOException;
import java.awt.*;

public class BuiltinPackages


{
public static void main(String[] args) throws IOException
{
//lang package
String text = "Hello, World!";
System.out.println(text.toLowerCase());
//util package
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println(list);
//io package
File f = new File("example.txt");
FileWriter fw = new FileWriter(f);
fw.write("Hello, File!");
fw.close();
//awt package
Frame fr = new Frame("My First Frame");
fr.setSize(300, 200);
fr.setVisible(true);
}
}

B.Tech (CSE-DS)-II-II Sem Page 13


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

2. User Defined Packages

In Java, user-defined packages allow you to organize your classes, interfaces,


and sub-packages into separate namespaces for better management and structure.

By grouping related classes into packages, you can avoid naming conflicts and
improve code readability and maintainability.

How to Create and Use User-Defined Packages

Steps to Create a User-Defined Package:

1. Create a Package: To define a user-defined package, use the package keyword at the
top of your Java source file.
2. Compile the Class: After defining the package, compile the Java file from the
directory above the package directory.
3. Import the Package: If you want to use classes from a package in another class, use
the import keyword.

B.Tech (CSE-DS)-II-II Sem Page 14


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Let's go through an example where we create a vehicle package, define classes related
to vehicles in that package, and then access those classes from another package.

Steps:

1. Create a vehicle package with classes like Vehicle and Car.


2. Create a Main class in a different package to access and use those classes.

Step 1: Creating the vehicle Package


First, we create a package called vehicle and add two classes: Vehicle and Car.
File: Vehicle.java (Inside vehicle package)

package vehicle;

// Vehicle class with basic properties and methods


public class Vehicle
{
private String brand;
private int year;

// Constructor
public Vehicle(String brand, int year)
{
this.brand = brand;
this.year = year;
}

// Getter and setter methods


public String getBrand()
{
return brand;
}

public void setBrand(String brand)


{
this.brand = brand;
}

public int getYear()


{
return year;
}

B.Tech (CSE-DS)-II-II Sem Page 15


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

public void setYear(int year)


{
this.year = year;
}
// Method to display basic vehicle information
public void displayInfo()
{
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

File: Car.java (Inside vehicle package)

package vehicle;

// Car class extends Vehicle and adds more functionality


public class Car extends Vehicle
{
private int doors;
// Constructor
public Car(String brand, int year, int doors)
{
super(brand, year); // Calling the superclass (Vehicle) constructor
this.doors = doors;
}
// Getter and setter methods
public int getDoors()
{
return doors;
}
public void setDoors(int doors)
{
this.doors = doors;
}
// Overridden method to display information about the car
@Override
public void displayInfo()
{
super.displayInfo(); // Call the displayInfo of Vehicle
System.out.println("Doors: " + doors);
}
}

B.Tech (CSE-DS)-II-II Sem Page 16


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Step 2: Creating the Main Class to Access the vehicle Package

Now, in a different package, we create a Main class to demonstrate how to use the
Vehicle and Car classes.

File: Main.java (In the default package or another package)

//Main.java
import vehicle.Vehicle;
import vehicle.Car;

public class Main


{
public static void main(String[] args)
{
// Create a Vehicle object
Vehicle v = new Vehicle("Toyota", 2020);
v.displayInfo();

// Create a Car object (which is a subclass of Vehicle)


Car c = new Car("Honda", 2022, 4);
c.displayInfo(); // It will also display Vehicle's info
}
}
Explanation:

1. vehicle Package:
o The Vehicle class has basic properties such as brand and year, along with
methods to get and set those properties. It also has a displayInfo() method to
print the vehicle's information.
o The Car class extends Vehicle and adds a doors property, representing the
number of doors in the car. It overrides the displayInfo() method to include the
number of doors in the output.
2. Main Class:
o The Main class imports the Vehicle and Car classes from the vehicle
package using the import statement.
o It then creates instances of both the Vehicle and Car classes and calls their
displayInfo() methods.

B.Tech (CSE-DS)-II-II Sem Page 17


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Directory Structure:

To compile and run the above code, your directory structure should look like this:

bin/

├── vehicle/
│ ├── Vehicle.java
│ └── Car.java

└── Main.java

How to Compile and Run:

1. Compile the classes & Run Main Class:

Understanding CLASSPATH
In Java, the CLASSPATH is an environment variable that tells the Java Virtual
Machine (JVM) and Java compiler where to look for compiled Java class files and
other resources like libraries (JAR files) when executing a program.

When you run a Java program, the JVM needs to find the classes that are part of
your program. By default, the JVM looks for classes in the current directory. However,
if your classes are located in different directories or JAR files, you need to specify
these locations via the CLASSPATH environment variable.
What it can contain:

 Directories: These contain compiled .class files.


 JAR files: Java Archive files, which package multiple .class files and associated
resources into a single file.

B.Tech (CSE-DS)-II-II Sem Page 18


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

Creating a JAR file

Whenever a developer wants to distribute a version of his software, then all he


want is to distribute a single file and not a directory structure filled with class files.
JAR files were designed for this purpose. A JAR file can contain both class files and
other file types like sound and image files which may be included in the project. All
the files in a JAR file are compressed using a format similar to zip.

A jar file is created using jar tool. The general command looks somewhat like this:

jar options jar-file [manifest-file] file1 file2 file3 ...

 jar – file : name of jar file on which you want to use jar tool.
 file1, file2, file3 : files which you want to add inside a jar file. manifest-file is
the name of file which contains manifest of that jar file, giving manifest-file as
an argument is entirely optional.
 c : Creates a new or empty archive and adds files to it. If any of the specified
file name are directories, then the jar program processes them recursively.
 C : Temporarily changes the directory.
 e : Creates an entry point in the manifest.
 f : Specifies the JAR file name as the second command-line argument. If this
parameter is missing, jar will write the result to standard output (when creating
a JAR file)or read it from standard input(when extracting or tabulating a JAR
file).
 i : Creates an index file.
 m : Adds a manifest file to the JAR file. A manifest is a description of the
archive contents and origin. Every archive has a default manifest, but you can
supply your own if you want to authenticate the contents of the archive.
 M : Does not create a manifest file for the entries.
 t : Displays the table of contents.
 u : Updates an existing JAR file.
 v : Generates verbose output.
 x : Extract files. If you supply one or more file names, only those files are
extracted Otherwise, all files are extracted.

B.Tech (CSE-DS)-II-II Sem Page 19


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

1. Directory Structure:
To compile and run the above code, your directory structure should look like this:
bin/

├── vehicle/
│ ├── Vehicle.java
│ └── Car.java

└── Main.java
2. Compile the Java Files

To compile the Java files, navigate to the src directory and compile the .java files:

This will compile the Java files and place the resulting .class files in the bin directory,
following the package structure.

3. Create the Manifest File

To specify the entry point of your application (the class with the main method), you
need to create a manifest file with the Main-Class attribute. The manifest file will tell
the JVM which class to run when you execute the JAR file.

Create a directory structure like this:

/MyProject
/META-INF
MANIFEST.MF

In the MANIFEST.MF file, add the following:


Manifest-Version: 1.0
Main-Class: Main

 Main-Class: The fully qualified class name of the class that contains the main
method to execute. In this case, Main.

B.Tech (CSE-DS)-II-II Sem Page 20


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

4. Create the JAR File

You can now create the JAR file using the jar command. Use the -m option to
specify your custom MANIFEST.MF file and the -C option to include your compiled
.class files from the bin directory.

Run the following command:

jar cmf META-INF/MANIFEST.MF myapp.jar -C bin/ .

 c: Create a new JAR file.


 m: Specify the manifest file.
 f: Specify the JAR file name (myapp.jar).
 -C bin/: Include the compiled .class files from the bin directory.

After running the command, the myapp.jar file will be created, containing the classes
and manifest.

5. Run the JAR File

Once the JAR file is created, you can run it using the java -jar command. The java -jar
command will automatically use the Main-Class attribute from the manifest file to
determine which class to execute.

To run the JAR file:

B.Tech (CSE-DS)-II-II Sem Page 21


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-II

How to set CLASSPATH:

You can set the CLASSPATH

 Temporarily or
 Permanently

Temporarily (in a command line):

To set the CLASSPATH temporarily for a session (only for the current command
prompt), you can use the following:

set CLASSPATH=C:\path\to\classes;C:\path\to\jarfile.jar

Permanently (in System Variable at as Environment variables):

Set the CLASSPATH variable:

C:\path\to\your\bin;C:\path\to\libs\library1.jar;C:\path\to\libs\library2.jar

B.Tech (CSE-DS)-II-II Sem Page 22

You might also like