0% found this document useful (0 votes)
5 views11 pages

Interfaces in Java

The document provides an overview of interfaces and packages in Java, detailing how to define, implement, and extend interfaces, as well as how to create and use packages. It explains access modifiers, the CLASSPATH variable, and generic programming, along with examples of casting objects and using the instanceof operator. Additionally, it covers the java.util package and its common classes for collections, date and time, and miscellaneous utilities.

Uploaded by

Umar Yousuff
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5 views11 pages

Interfaces in Java

The document provides an overview of interfaces and packages in Java, detailing how to define, implement, and extend interfaces, as well as how to create and use packages. It explains access modifiers, the CLASSPATH variable, and generic programming, along with examples of casting objects and using the instanceof operator. Additionally, it covers the java.util package and its common classes for collections, date and time, and miscellaneous utilities.

Uploaded by

Umar Yousuff
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

Interfaces in Java

Defining an Interface
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
constructors.
Syntax:
java
Copy code
public interface MyInterface {
// Constant declarations
int MY_CONSTANT = 10;

// Method signatures
void method1();
int method2(String param);

// Default method
default void defaultMethod() {
System.out.println("This is a default method.");
}

// Static method
static void staticMethod() {
System.out.println("This is a static method.");
}
}
Implementing an Interface
A class that implements an interface must provide implementations for all methods declared in the interface.
Syntax:
java
Copy code
public class MyClass implements MyInterface {
@Override
public void method1() {
System.out.println("Implementation of method1");
}

@Override
public int method2(String param) {
return param.length();
}
}
Extending an Interface
An interface can extend another interface, meaning it inherits all the abstract methods of the parent interface.
Syntax:
public interface AdvancedInterface extends MyInterface {
void advancedMethod();
}
Example:
public class AdvancedClass implements AdvancedInterface {
@Override
public void method1() {
System.out.println("Implementation of method1");
}

@Override
public int method2(String param) {
return param.length();
}

@Override
public void advancedMethod() {
System.out.println("Implementation of advancedMethod");
}
}
Packages in Java
A package is a namespace for organizing classes and interfaces in a logical manner. It helps to avoid class
name conflicts and to control access to classes.
Creating a Package
To create a package, you need to include a package statement at the top of your Java source file, followed by
the package name.
Syntax:
package mypackage;

public class MyClass {


// Class contents
}
Using a Package
To use classes or interfaces from another package, you need to import the package using the import
statement.
Syntax:
import mypackage.MyClass;

public class Test {


public static void main(String[] args) {
MyClass obj = new MyClass();
}
}
Default Package
If you do not specify a package, your class or interface will be placed in an unnamed package (default
package). However, it's a good practice to define a package for your classes.
Subpackages
Packages can have subpackages. Subpackages are regular packages, and there is no hierarchical relationship
between a package and its subpackage.
Syntax:
package mypackage.subpackage;

public class MySubClass {


// Class contents
}
Access Modifiers and Packages
Access modifiers control the accessibility of classes, methods, and fields.
 Default: Accessible only within the same package.
 Public: Accessible from any other class.
 Protected: Accessible within the same package and subclasses.
 Private: Accessible only within the same class.
Example of a Java Package
File: mypackage/MyClass.java
java
Copy code
package mypackage;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass in mypackage");
}
}
File: mypackage/subpackage/MySubClass.java
package mypackage.subpackage;

public class MySubClass {


public void display() {
System.out.println("Hello from MySubClass in mypackage.subpackage");
}
}
File: Test.java
import mypackage.MyClass;
import mypackage.subpackage.MySubClass;

public class Test {


public static void main(String[] args) {
MyClass obj1 = new MyClass();
obj1.display();
MySubClass obj2 = new MySubClass();
obj2.display();
}
}

CLASSPATH Variable
The CLASSPATH variable in Java is used by the Java Runtime Environment (JRE) and Java compiler to
locate classes and packages needed for execution and compilation.
 Setting CLASSPATH: You can set the CLASSPATH variable in the environment or specify it at
runtime.
Setting CLASSPATH in the Environment:
 On Windows:
set CLASSPATH=C:\path\to\classes;C:\another\path\to\classes;.
 On Unix/Linux:
export CLASSPATH=/path/to/classes:/another/path/to/classes:.
Setting CLASSPATH at Runtime:
 Using -cp or -classpath option with java and javac commands:
javac -cp .;C:\path\to\classes MyClass.java
java -cp .;C:\path\to\classes MyClass
 Default CLASSPATH: If the CLASSPATH variable is not set, the default is the current directory (.).
Access Protection
Access modifiers in Java control the visibility and accessibility of classes, methods, and fields. There are
four types of access modifiers:
1. Default (Package-Private): Accessible only within the same package.
class MyClass {
void myMethod() { }
}
2. Public: Accessible from any other class.
public class MyClass {
public void myMethod() { }
}
3. Protected: Accessible within the same package and by subclasses.
public class MyClass {
protected void myMethod() { }
}
4. Private: Accessible only within the same class.
public class MyClass {
private void myMethod() { }
}
Importing Packages
The import statement is used to bring other classes or entire packages into visibility.
 Single Type Import: Imports a specific class.
import java.util.ArrayList;
 On-Demand Import: Imports all classes from a package.
import java.util.*;
 Static Import: Imports static members of a class.

import static java.lang.Math.PI;


import static java.lang.Math.sqrt;
java.util Package
The java.util package contains the collections framework, legacy collection classes, event model, date and
time facilities, internationalization, and miscellaneous utility classes.
Common Classes in java.util:
1. Collections Framework:
o List: ArrayList, LinkedList
o Set: HashSet, LinkedHashSet, TreeSet
o Map: HashMap, LinkedHashMap, TreeMap, Hashtable
o Queue: PriorityQueue, LinkedList
o Stack: Stack
Example:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;

public class CollectionsExample {


public static void main(String[] args) {
// List example
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");

// Set example
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");

// Map example
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
}
}
2. Date and Time:
o Date: Date
o Calendar: Calendar, GregorianCalendar
o TimeZone: TimeZone
Example:
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;

public class DateTimeExample {


public static void main(String[] args) {
// Date example
Date date = new Date();
System.out.println("Current Date: " + date);

// Calendar example
Calendar calendar = Calendar.getInstance();
System.out.println("Current Year: " + calendar.get(Calendar.YEAR));

// TimeZone example
TimeZone timeZone = TimeZone.getDefault();
System.out.println("Time Zone: " + timeZone.getDisplayName());
}
}
3. Miscellaneous:
o Random: Random
o Scanner: Scanner
o Properties: Properties
Example:
import java.util.Random;
import java.util.Scanner;
import java.util.Properties;

public class MiscellaneousExample {


public static void main(String[] args) {
// Random example
Random random = new Random();
System.out.println("Random Number: " + random.nextInt());

// Scanner example
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
System.out.println("You entered: " + input);

// Properties example
Properties properties = new Properties();
properties.setProperty("username", "admin");
properties.setProperty("password", "1234");
System.out.println("Username: " + properties.getProperty("username"));
}
}
This should give you a comprehensive understanding of the CLASSPATH variable, access protection,
importing packages, and the java.util package in Java.
Generic Programming
Generic programming in Java is a way to write code that can work with different types of objects while still
being type-safe. This means you can write a single class, method, or interface that can handle different data
types without having to rewrite the code for each type.

Casting Objects
Casting in Java is a way to convert an object from one type to another. There are two main types of casting:
upcasting and downcasting.
Upcasting
Upcasting is casting a subclass object to a superclass type. This is safe and always allowed because the
subclass object has all the properties and methods of the superclass.
For example:
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Woof");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
Animal myAnimal = myDog; // Upcasting
myAnimal.makeSound(); // This works, calls Animal's makeSound method
}
}
Downcasting
Downcasting is casting a superclass object to a subclass type. This can be risky because the superclass might
not have all the properties and methods of the subclass, so you need to ensure that the object is actually an
instance of the subclass.
For example:
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Woof");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting
Dog myDog = (Dog) myAnimal; // Downcasting
myDog.bark(); // This works because myAnimal is actually a Dog
}
}

Instance of operator

The instanceof operator in Java is used to test whether an object is an instance of a specific class or a
subclass of that class.
Syntax : object instanceof ClassName
class Animal {
}

class Dog extends Animal {


}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Dog();

// Check if myAnimal is an instance of Dog


if (myAnimal instanceof Dog) {
System.out.println("myAnimal is a Dog");
} else {
System.out.println("myAnimal is not a Dog");
}

// Check if myAnimal is an instance of Animal


if (myAnimal instanceof Animal) {
System.out.println("myAnimal is an Animal");
} else {
System.out.println("myAnimal is not an Animal");
}
}
}

OUTPUT
myAnimal is a Dog
myAnimal is an Animal

Explanation
 myAnimal instanceof Dog: This returns true because myAnimal is actually an instance of Dog.
 myAnimal instanceof Animal: This also returns true because Dog is a subclass of Animal, so any
Dog is also an Animal.

You might also like