JAVA-Notes-Unit-2_Part 2
JAVA-Notes-Unit-2_Part 2
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.");
}
}
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.
System.out.println("\nTruck Actions:");
t.start();
t.accelerate();
t.honk();
t.stop();
}
}
Abstract class can have final, non- Interface has only static and final
6.
final, static and non-static variables. variables.
Example: Example:
public abstract class Shape public interface Drawable
11. { {
public abstract void draw(); void draw();
} }
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.
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.
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.
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:
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:
4. java.net Package
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
import java.lang.*;
import java.util.ArrayList;
import java.io.*;
import java.io.IOException;
import java.awt.*;
By grouping related classes into packages, you can avoid naming conflicts and
improve code readability and maintainability.
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.
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:
package vehicle;
// Constructor
public Vehicle(String brand, int year)
{
this.brand = brand;
this.year = year;
}
package vehicle;
Now, in a different package, we create a Main class to demonstrate how to use the
Vehicle and Car classes.
//Main.java
import vehicle.Vehicle;
import vehicle.Car;
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.
Directory Structure:
To compile and run the above code, your directory structure should look like this:
bin/
│
├── vehicle/
│ ├── Vehicle.java
│ └── Car.java
│
└── Main.java
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:
A jar file is created using jar tool. The general command looks somewhat like this:
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.
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.
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.
/MyProject
/META-INF
MANIFEST.MF
Main-Class: The fully qualified class name of the class that contains the main
method to execute. In this case, Main.
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.
After running the command, the myapp.jar file will be created, containing the classes
and manifest.
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.
Temporarily or
Permanently
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
C:\path\to\your\bin;C:\path\to\libs\library1.jar;C:\path\to\libs\library2.jar