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

java unit-2

Inheritance in Java allows a class (subclass) to inherit properties and behaviors from another class (superclass), promoting code reusability and method overriding. There are three types of inheritance: single, multilevel, and hierarchical, with the 'super' keyword used to access parent class members. The Object class serves as the root of all classes in Java, and polymorphism enables methods to be executed in different ways based on the object type at runtime.

Uploaded by

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

java unit-2

Inheritance in Java allows a class (subclass) to inherit properties and behaviors from another class (superclass), promoting code reusability and method overriding. There are three types of inheritance: single, multilevel, and hierarchical, with the 'super' keyword used to access parent class members. The Object class serves as the root of all classes in Java, and polymorphism enables methods to be executed in different ways based on the object type at runtime.

Uploaded by

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

Java Inheritance (Subclass and Superclass)

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. In inheritance you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class and also you can add new methods and fields in your current.

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.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.In java programming, multiple and hybrid inheritance is supported through
interface only. We will learn about interfaces later.
Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

1. class Animal{
2. void eat()
3. {
4. System.out.println("eating...");
5. } }
6. class Dog extends Animal
7. {
8. void bark()
9. {
10. System.out.println("barking...");
11. } }
12. class TestInheritance
13. {
14. public static void main(String args[])
15. {
16. Dog d=new Dog();
17. d.bark();
18. d.eat();
19. }}

Output:

barking...

eating...
Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark(){System.out.println("barking...");
11. }
12. }
13. class BabyDog extends Dog
14. {
15. void weep(){System.out.println("weeping...");
16. }
17. }
18. class TestInheritance2
19. {
20. public static void main(String args[])
21. {
22. BabyDog d=new BabyDog();
23. d.weep();
24. d.bark();
25. d.eat();
26. }}
Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

File: TestInheritance3.java
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14. }
15. class Cat extends Animal
16. {
17. void meow()
18. {
19. System.out.println("meowing...");
20. }
21. }
22. class TestInheritance3
23. {
24. public static void main(String args[]){
25. Cat c=new Cat();
26. c.meow();
27. c.eat();
28. //c.bark();//C.T.Error
29. }}
Output:

meowing...
eating...

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1) super is 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.

1. class Animal
2. {
3. String color="white";
4. }
5. class Dog extends Animal
6. {
7. String color="black";
8. void printColor()
9. {
10. System.out.println(color); //prints color of Dog class
11. System.out.println(super.color); //prints color of Animal class
12. }
13. }
14. class TestSuper1
15. {
16. public static void main(String args[])
17. {
18. Dog d=new Dog();
19. d.printColor();
20. }}

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.

1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void eat()
11. {
12. System.out.println("eating bread...");
13. }
14. void bark()
15. {
16. System.out.println("barking...");
17. }
18. void work()
19. {
20. super.eat();
21. bark();
22. }
23. }
24. class TestSuper2
25. {
26. public static void main(String args[])
27. {
28. Dog d=new Dog();
29. d.work();
30. }}

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:

1. class Animal
2. {
3. Animal()
4. {
5. System.out.println("animal is created");
6. }
7. }
8. class Dog extends Animal
9. {
10. Dog()
11. {
12. super();
13. System.out.println("dog is created");
14. }
15. }
16. class TestSuper3
17. {
18. public static void main(String args[])
19. {
20. Dog d=new Dog();
21. }}

Preventing Inheritance

final is a keyword in java used for restricting some functionalities. We can declare
variables, methods, and classes with the final keyword. The main reason to
prevent inheritance is to make sure the way a class behaves is not corrupted by a subclass.

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run()
4. {
5. speedlimit=400;
6. }
7. public static void main(String args[]){
8. Bike9 obj=new Bike9();
9. obj.run();
10. }
11. }//end of class

2) Java final method

If you make any method as final, you cannot override it.

Example of final method


1. class Bike
2. {
3. final void run()
4. {
5. System.out.println("running");
6. }
7. }
8.
9. class Honda extends Bike
10. {
11. void run()
12. {
13. System.out.println("running safely with 100kmph");
14. }
15.
16. public static void main(String args[])
17. {
18. Honda honda= new Honda();
19. honda.run();
20. }
21. }

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class


1. final class Bike
2. {
3. }
4.
5. class Honda1 extends Bike
6. {
7. void run()
8. {
9. System.out.println("running safely with 100kmph");
10. }
11.
12. public static void main(String args[])
13. {
14. Honda1 honda= new Honda1();
15. honda.run();
16. }
17. }

Object class in Java


The Object class is the parent class of all the classes in java by default. In other words, it is
the top most class of java.

The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any
type like Employee, Student etc, we can use Object class reference to refer that object. For
example:

Object obj=getObject ();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description
returns the Class class object of this object. The Class
public final Class getClass() class can further be used to get the metadata of this
class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.

public String toString() returns the string representation of this object.

wakes up single thread, waiting on this object's


public final void notify()
monitor.

wakes up all the threads, waiting on this object's


public final void notifyAll()
monitor.

causes the current thread to wait for the specified


public final void wait(long timeout)throws
milliseconds, until another thread notifies (invokes
InterruptedException
notify() or notifyAll() method).

causes the current thread to wait for the specified


public final void wait(long timeout,int
milliseconds and nanoseconds, until another thread
nanos)throws InterruptedException
notifies (invokes notify() or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).

is invoked by the garbage collector before object is


protected void finalize()throws Throwable
being garbage collected.

POLYMORPHISM
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance. This allows us to perform a single action in different
ways.

class Animal {

public void animalSound() {

System.out.println("The animal makes a sound");

class Pig extends Animal {

public void animalSound() {

System.out.println("The pig says: wee wee");

class Dog extends Animal {

public void animalSound() {

System.out.println("The dog says: bow wow");

class Main {

public static void main(String[] args) {

Animal myAnimal = new Animal(); // Create a Animal object

Animal myPig = new Pig(); // Create a Pig object

Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();

myPig.animalSound();
myDog.animalSound();

static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding


1. class Dog
2. {
3. private void eat()
4. {System.out.println("dog is eating...");
5. }
6.
7. public static void main(String args[])
8. {
9. Dog d1=new Dog();
10. d1.eat();
11. }
12. }

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding


1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("animal is eating...");
6. }
7. }
8.
9. class Dog extends Animal
10. {
11. void eat()
12. {
13. System.out.println("dog is eating...");
14. }
15.
16. public static void main(String args[])
17. {
18. Animal a=new Dog();
19. a.eat();
20. }
21. }

Output:dog is eating...

In the above example object type cannot be determined by the compiler, because the instance of Dog is also an
instance of Animal.So compiler doesn't know its type, only its base type.

Method Overriding in Java

If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

1. Method overriding is used to provide the specific implementation of a method that is


already provided by its superclass.
2. Method overriding is used for runtime polymorphism.
3. Method overriding allows subclasses to reuse and build upon the functionality
provided by their superclass, reducing redundancy and promoting modular code
design.
4. Subclasses can override methods to tailor them to their specific needs or to implement
specialized behavior that is unique to the subclass.
5. Method overriding enables dynamic method dispatch, where the actual method
implementation to be executed is determined at runtime based on the type of object,
supporting flexibility and polymorphic behavior.

Rules for Java Method Overridingh2h3>

1. Same Method Name: The overriding method in the subclass must have the same
name as the method in the superclass that it is overriding.
2. Same Parameters: The overriding method must have the same number and types of
parameters as the method in the superclass. This ensures compatibility and
consistency with the method signature defined in the superclass.
3. IS-A Relationship (Inheritance): Method overriding requires an IS-A relationship
between the subclass and the superclass. This means that the subclass must inherit
from the superclass, either directly or indirectly, to override its methods.
4. Same Return Type or Covariant Return Type: The return type of the overriding
method can be the same as the return type of the overridden method in the superclass,
or it can be a subtype of the return type in the superclass. This is known as the
covariant return type, introduced in Java 5.
5. Access Modifier Restrictions: The access modifier of the overriding method must be
the same as or less restrictive than the access modifier of the overridden method in the
superclass. Specifically, a method declared as public in the superclass can be
overridden as public or protected but not as private. Similarly, a method declared as
protected in the superclass can be overridden as protected or public but not as private.
A method declared as default (package-private) in the superclass can be overridden
with default, protected, or public, but not as private.
6. No Final Methods: Methods declared as final in the superclass cannot be overridden
in the subclass. This is because final methods cannot be modified or extended.
7. No Static Methods: Static methods in Java are resolved at compile time and cannot
be overridden. Instead, they are hidden in the subclass if a method with the same
signature is defined in the subclass.

Example of Method Overriding


In this example, we have defined the run method in the subclass as defined in the parent
class, but it has some specific implementation. The method's name and parameters are the
same, and there is an IS-A relationship between the classes, so there is method overriding.

1. class Vehicle
2. {
3. void run()
4. {
5. System.out.println("Vehicle is running");
6. }
7. }
8. class Bike2 extends Vehicle
9. {
10. void run()
11. {
12. System.out.println("Bike is running safely");
13. }
14. public static void main(String args[])
15. {
16. Bike2 obj = new Bike2();
17. obj.run();
18. }
19. }

Output:Bike is running safely

class Bank
1. {
2. int getRateOfInterest()
3. {
4. return 0;
5. }
6. }
7. class SBI extends Bank
8. {
9. int getRateOfInterest()
10. {
11. return 8;
12. }
13. }
14.
15. class ICICI extends Bank
16. {
17. int getRateOfInterest()
18. {
19. return 7;
20. }
21. }
22. class AXIS extends Bank
23. {
24. int getRateOfInterest()
25. {
26. return 9;
27. }
28. }
29. class Test2
30. {
31. public static void main(String args[])
32. {
33. SBI s=new SBI();
34. ICICI i=new ICICI();
35. AXIS a=new AXIS();
36. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
37. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
38. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
39. }
40. }
Output:

SBI Rate of Interest: 8


ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

1. abstract class Bike


2. {
3. abstract void run();
4. }
5. class Honda4 extends Bike
6. {
7. void run()
8. {
9. System.out.println("running safely");
10. }
11. public static void main(String args[])
12. {
13. Bike obj = new Honda4();
14. obj.run();
15. }
16. }

17. running safely

INTERFACES:

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.
Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and static methods also.

2) Abstract class doesn't support multiple


Interface supports multiple inheritance.
inheritance.

3) Abstract class can have final, non-final, static and


Interface has only static and final variables.
non-static variables.

4) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.

5) The abstract keyword is used to declare abstract


The interface keyword is used to declare interface.
class.

6) An abstract class can extend another Java class and


An interface can extend another Java interface only.
implement multiple Java interfaces.

7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".

8) A Java abstract class can have class members like


Members of a Java interface are public by default.
private, protected, etc.

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

1. /Creating interface that has 4 methods


2. interface A{
3. void a();//bydefault, public and abstract
4. void b();
5. void c();
6. void d();
7. }
8.
9. //Creating abstract class that provides the implementation of one method of A interface
10. abstract class B implements A{
11. public void c(){System.out.println("I am C");}
12. }
13.
14. //Creating subclass of abstract class, now we need to provide the implementation of rest of th
e methods
15. class M extends B{
16. public void a(){System.out.println("I am a");}
17. public void b(){System.out.println("I am b");}
18. public void d(){System.out.println("I am d");}
19. }
20.
21. //Creating a test class that calls the methods of A interface
22. class Test5{
23. public static void main(String args[]){
24. A a=new M();
25. a.a();
26. a.b();
27. a.c();
28. a.d();
29. }}

Output:

I am a
I am b
I am c
I am d

INTERFACE:

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

Interfaces can have abstract methods and variables. It cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.


Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

The 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.

Example:

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Difference Between Class and Interface


Although Class and Interface seem the same there have certain differences between Classes
and Interface. The major differences between a class and an interface are mentioned below:
Class Interface

In an interface, you must initialize variables


In class, you can instantiate variables and
as they are final but you can’t create an
create an object.
object.

A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.

The access specifiers used with classes are In Interface only one specifier is used-
private, protected, and public. Public.

IMPLEMENTATION:

Implementation: To implement an interface, we use the keyword implements


Java
// Java program to demonstrate working of
// interface

import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1 {

// Implementing the capabilities of


// interface.
public void display(){
System.out.println("Geek");
}

// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}

Output
Geek
10

Multiple Inheritance in Java Using Interface


Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes.
But we can use multiple inheritances in Java using Interface. let us check this with an
example.
Example:
Java

// Java program to demonstrate How Diamond Problem


// Is Handled in case of Default Methods

// Interface 1
interface API {
// Default method
default void show()
{

// Print statement
System.out.println("Default API");
}
}

// Interface 2
// Extending the above interface
interface Interface1 extends API {
// Abstract method
void display();
}
// Interface 3
// Extending the above interface
interface Interface2 extends API {
// Abstract method
void print();
}

// Main class
// Implementation class code
class TestClass implements Interface1, Interface2 {
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}
// Main driver method
public static void main(String args[])
{
// Creating object of this class
// in main() method
TestClass d = new TestClass();

// Now calling the methods from both the interfaces


d.show(); // Default method from API
d.display(); // Overridden method from Interface1
d.print(); // Overridden method from Interface2
}
}

Output

Default API
Display from Interface1
Print from Interface2
Extending Interfaces
One interface can inherit another by the use of keyword extends. When a class implements
an interface that inherits another interface, it must provide an implementation for all
methods required by the interface inheritance chain.
Program 1:
Java

interface A {
void method1();
void method2();
}
// B now includes method1 and method2
interface B extends A {
void method3();
}
// the class must implement all method of A and B.
class gfg implements B {
public void method1()
{
System.out.println("Method 1");
}
public void method2()
{
System.out.println("Method 2");
}
public void method3()
{
System.out.println("Method 3");
}
}

Java Inner Classes (Nested Classes)

1. Java Inner classes


2. Advantage of Inner class
3. Difference between nested class and inner class
4. Types of Nested classes

Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.

Additionally, it can access all the members of the outer class, including private data members
and methods.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
Advantage of Java inner classes
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.

Need of Java Inner class

Sometimes users need to program a class in such a way so that no other class can access it.
Therefore, it would be better if you include it within other classes.

If all the class objects are a part of the outer object then it is easier to nest that class inside the
outer class. That way all the outer class can access all the objects of the inner class.

Difference between nested class and inner class in Java


An inner class is a part of a nested class. Non-static nested classes are known as inner classes.

Types of Nested classes


There are two types of nested classes non-static and static nested classes. The non-static
nested classes are also known as inner classes.

o Non-static nested class (inner class)

o Member inner class


o Anonymous inner class
o Local inner class
o Static nested class

Type Description

Member Inner Class A class created within class and outside method.

A class created for implementing an interfac


Anonymous Inner Class
extending class. The java compiler decides its nam

Local Inner Class A class was created within the method.

Static Nested Class A static class was created within the class.

Nested Interface An interface created within class or interface.

There are certain advantages associated with inner classes are as follows:
 Making code clean and readable.
 Private methods of the outer class can be accessed, so bringing a new dimension and
making it closer to the real world.
 Optimizing the code module.
Types of Inner Classes
There are basically four types of inner classes in java.
1. Nested Inner Class
2. Method Local Inner Classes
3. Static Nested Classes
4. Anonymous Inner Classes

Nested Inner Class


It can access any private instance variable of the outer class. Like any other instance
variable, we can have access modifier private, protected, public, and default modifier. Like
class, an interface can also be nested and can have access specifiers.
Example 1A
Java
// Java Program to Demonstrate Nested class

// Class 1
// Helper classes
class Outer {

// Class 2
// Simple nested inner class
class Inner {

// show() method of inner class


public void show()
{

// Print statement
System.out.println("In a nested class method");
}
}
}

// Class 2
// Main class
class Main {

// Main driver method


public static void main(String[] args)
{

// Note how inner class object is created inside


// main()
Outer.Inner in = new Outer().new Inner();
// Calling show() method over above object created
in.show();
}
}

Output
In a nested class method

Note: We can not have a static method in a nested inner class because an inner class is
implicitly associated with an object of its outer class so it cannot define any static method
for itself.

Static Nested Classes


Static nested classes are not technically inner classes. They are like a static member of outer
class.
Example
Java
// Java Program to Illustrate Static Nested Classes

// Importing required classes


import java.util.*;

// Class 1
// Outer class
class Outer {

// Method
private static void outerMethod()
{

// Print statement
System.out.println("inside outerMethod");
}

// Class 2
// Static inner class
static class Inner {

public static void display()


{

// Print statement
System.out.println("inside inner class Method");

// Calling method inside main() method


outerMethod();
}
}
}
// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

// Calling method static display method rather than an instance of that class.
Outer.Inner.display();
}
}

Output
inside inner class Method
inside outerMethod
Anonymous Inner Classes
Anonymous inner classes are declared without any name at all. They are created in two
ways.
 As a subclass of the specified type
 As an implementer of the specified interface
Way 1: As a subclass of the specified type
Example:
Java
// Java Program to Illustrate Anonymous Inner classes
// Declaration Without any Name
// As a subclass of the specified type

// Importing required classes


import java.util.*;

// Class 1
// Helper class
class Demo {

// Method of helper class


void show()
{
// Print statement
System.out.println(
"i am in show method of super class");
}
}

// Class 2
// Main class
class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
// Method 1
// show() method
void show()
{
// Calling method show() via super keyword
// which refers to parent class
super.show();

// Print statement
System.out.println("i am in Flavor1Demo class");
}
};

// Method 2
// Main driver method
public static void main(String[] args)
{
// Calling show() method inside main() method
d.show();
}
}

Output
i am in show method of super class
i am in Flavor1Demo class

Java Package

1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class

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

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Creating and accessing package:

Simple example of java package


The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename


For example

1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represen
current folder.

Importing packages:

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }

Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }

Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }

Output:Hello

Note: If you import a package, sub packages will not be imported.


If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the sub packages. Hence, you need to import the sub
package as well.

CLASSPATH in Java

Last Updated : 06 Oct, 2021



Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and


interfaces. Packages are used for:
 Preventing naming conflicts. For example, there can be two classes with the name
Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations, and annotations
easier
 Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier) is accessible by classes in the same
package only.
Packages can be considered as data encapsulation (or data-hiding). Here we will be
discussing the responsibility of the CLASSPATH environment variable while programming
in Java as we move forward we for sure short need usage of importing statements.
Illustration:
import org.company.Menu
What does this import mean? It makes the Menu class available in the package org.company
to our current class. Such that when we call the below command as follows:
Menu menu = new Menu();
Example
 Java

// Java Program to Illustrate Usage of importing

// Classes from packages and sub-packages

// Here we are importing all classes from

// java.io (input-output package)

import java.io.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

{
// Print statement

System.out.println("I/O classes are imported from java.io package");

Output

I/O classes are imported from java.io package


This package provides for system input and output through data streams, serialization, and
the file system. Unless otherwise noted, passing a null argument to a constructor or method in
any class or interface in this package will cause a NullPointerException to be thrown. All the
classes listed here are imported or if we want to import a specific one then do use it as stated
below.
import java.util.Scanner ;
The JVM knows where to find the class Menu. Now, how will the JVM know this location?
It is impractical for it to go through every folder on your system and search for it. Thus, using
the CLASSPATH variable we provide it the place where we want it to look. We put
directories and jars in the CLASSPATH variable.
Set the CLASSPATH in JAVA in Windows
Command Prompt:
Open the Command Prompt.
Use the following command to set the CLASSPATH:
set CLASSPATH=.;C:\path\to\your\classes;C:\path\to\your\libraries
Note: The dot (.) represents the current directory, and the semicolon (;) is used as a
separator between different paths.
Example:
set CLASSPATH=.;C:\Users\GFG\JavaClasses;C:\Program Files\Java\libs
GUI:
1. Select Start
2. Go to the Control Panel
3. Select System and Security

4. Select Advanced System settings


5. Click on Environment Variables
6. Click on New under System Variables
7. Add CLASSPATH as variable name and path of files as a variable value.

8. Select OK.
Set the CLASSPATH on Linux
Command Line:
Find out where you have installed Java, basically, it’s in /usr/lib/jvm path. Set the
CLASSPATH in /etc/environment using
sudo <editor name> /etc/environment
Add the following lines,
CLASSPATH=".:/path/to/your/classes:/path/to/your/libraries"
export CLASSPATH
Note: Colon (:) is used as a separate directory and dot (.) is the default value of
CLASSPATH in the above command.
To check the current CLASSPATH, run
echo ${CLASSPATH}
Difference between PATH and CLASSPATH
 The PATH variable is used to specify the location of the Java binaries (e.g., java,
javac). It allows the system to locate the Java executables to compile and run programs.
 The CLASSPATH variable is used to specify the location of the Java class files and
libraries required for the program. It tells the JVM and compiler where to look for user-
defined classes and packages.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy