Java Unit-2
Java Unit-2
Uniti2 -- Inheritane
1.introduction
2. polymorphism
4. Interfaces
5. inner classes
6. packages
1.introduction of inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that 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. Moreover, you can add new methods and fields in your
current class also.
Syntax
class Super
{
.....
.....
}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[])
7. {
8. Programmer p=new Programmer();
9. System.out.println("Programmer salary is:"+p.salary);
10. System.out.println("Bonus of Programmer is:"+p.bonus);
11.}
12.}
Programmer salary is:40000.0
If you have multiple subclasses that inherit from a superclass, you can form an inheritance
hierarchy. Every subclass is-a or is a kind of the superclass. For example, here is an
inheritance hierarchy of Shapes. Square is-a Rectangle and a subclass of Rectangle.
Rectangle is-a Shape and a subclass of Shape. In Java, the class Object is at the top of
hierarchy. Every class in Java inherits from Object and is-an Object.
8
Note: 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.
Superclass can only be one: A superclass can have any number of subclasses.
But a subclass can have only one superclass. This is because Java does not
support multiple inheritances with classes. Although with interfaces, multiple
inheritances are supported by java.
note: if super class has parameterized constructor it should be called from child
class constructor other wise we get compile time error
Private member inheritance: A subclass does not inherit the private members
of its parent class. However, if the superclass has public or protected methods(like
getters and setters) for accessing its private fields, these can also be used by the
subclass.
File: TestInheritance.java
1. class Animal{
2. void eat()
3. {
9
4. System.out.println("eating...");
5. }
6. }
7. class Dog extends Animal{
8. void bark()
9. {
10.System.out.println("barking...");
11.}
12.}
13.class TestInheritance{
14.public static void main(String args[])
15.{
16.Dog d=new Dog();
17.d.bark();
18.d.eat();
19.}}
Output:
barking...
eating...
File: TestInheritance2.java
1. class Animal{
2. void eat()
3. {
4. System.out.println("eating...");
5. }
6. }
7. class Dog extends Animal{
8. void bark()
10
9. {
10.System.out.println("barking...");
11.}
12.}
13.class BabyDog extends Dog{
14.void weep()
15.{
16.System.out.println("weeping...");
17.}
18.}
19.class TestInheritance2{
20.public static void main(String args[]){
21.BabyDog d=new BabyDog();
22.d.weep();
23.d.bark();
24.d.eat();
25.}}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark()
6. {
7. System.out.println("barking...");
11
8. }
9. }
10.class Cat extends Animal{
11.void meow()
12.{
13.System.out.println("meowing...");
14.}
15.}
16.class TestInheritance3
17.{
18.public static void main(String args[]){
19.Cat c=new Cat();
20.c.meow();
21.c.eat();
22.//c.bark();//C.T.Error
23.}}
Output:
meowing...
eating...
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
12
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12.}
13.}
The class which inherits the properties of another class is called the subclass or
the child class. The class whose properties are inherited is known as the base class,
super class or the parent class.
The variables and methods by using Java Access Modifiers implements reusability of
existing code
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class
…….
….
13
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference 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. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor()
7. {
8. System.out.println(color);//prints color of Dog class
9. System.out.println(super.color);//prints color of Animal class
10.}
11.}
12.class TestSuper1{
13.public static void main(String args[]){
14.Dog d=new Dog();
14
15.d.printColor();
16.}}
Test it Now
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default. To access the
parent property, we need to use super keyword.
1. class Animal{
2. void eat()
3. {
4. System.out.println("eating...");
5. }
6. }
7. class Dog extends Animal
8. {
9. void eat()
10.{
11.System.out.println("eating bread...");
12.}
13.void bark()
14.{
15.System.out.println("barking...");
16.}
17.void work()
18.{
19.super.eat();
20.bark();
15
21.}
22.}
23.class TestSuper2{
24.public static void main(String args[]){
25.Dog d=new Dog();
26.d.work();
27.}}
Test it Now
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.
1. class Animal{
2. Animal()
3. {
4. System.out.println("animal is created");
5. }
6. }
7. class Dog extends Animal{
8. Dog(){
9. super();
10.System.out.println("dog is created");
11.}
12.}
13.class TestSuper3{
14.public static void main(String args[]){
16
15.Dog d=new Dog();
16.}}
Test it Now
Output:
animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is
no super() or this().
1. class Animal{
2. Animal()
3. {
4. System.out.println("animal is created");
5. }
6. }
7. class Dog extends Animal{
8. Dog()
9. {
10.System.out.println("dog is created");
11.}
12.}
13.class TestSuper4{
14.public static void main(String args[]){
15.Dog d=new Dog();
17
16.}}
Test it Now
Output:
animal is created
dog is created
What if the child class is not overriding any method: No need of
super
When child class doesn’t override the parent class method then we don’t need to use the
super keyword to call the parent class method. This is because in this case we have only
one version of each method and child class has access to the parent class methods so we
can directly call the methods of parent class without using super.
class Parentclass
{
void display(){
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
void printMsg(){
/* This would call method of parent class,
* no need to use super keyword because no other
* method with the same name is present in this class
*/
display();
}
public static void main(String args[]){
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
The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in
the static block only. We will have detailed learning of these. Let's first learn the basics
of final keyword.
1. You can initialize a final variable when it is declared.This approach is the most
common. A final variable is called blank final variable,if it is not initialized while
declaration. Below are the two ways to initialize a blank final variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.
1. class Bike10
2. {
3. final int speedlimit;//blank final variable
4.
20
5. Bike10()
6. {
7. speedlimit=70;
8. System.out.println(speedlimit);
9. }
10.
11. public static void main(String args[]){
12. new Bike10();
13. }
14.}
Test it Now
Output: 70
Example—2 : initializing final varible either in constructor or in instance
block
class Bike
{
final int speedlimit;//blank final variable
final int BREAKS;// blank final variable
{
BREAKS= 3;
}
Bike()
{
speedlimit=70;
System.out.println(speedlimit);
}
Bike(int x)
{
speedlimit=70;
}
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. {
3. final int speedlimit=90;//final variable
4. void run()
5. {
6. speedlimit=400;
7. }
8. public static void main(String args[])
9. {
10. Bike9 obj=new Bike9();
11. obj.run();
12. }
13.}//end of class
Test it Now
1. final class A
2. {
3. // methods and fields
4. }
5. // The following class is illegal.
6. class B extends A
7. {
8. // COMPILE-ERROR! Can't subclass A
9. }
The other use of final with classes is to create an immutable class like the
predefined String class.You can not make a class immutable without making it final.
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. Honda1 honda= new Honda1();
14. honda.run();
15. }
16.}
Test it Now
Therefore the Object class methods are available to all Java classes. Hence Object
class acts as a root of inheritance hierarchy in any Java Program.
Method Description
public final Class getClass() returns the Class class object of this object. The Class
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 final void notify() wakes up single thread, waiting on this object's
monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long causes the current thread to wait for the specified
25
public final void wait(long causes the current thread to wait for the specified
timeout,int nanos)throws milliseconds and nanoseconds, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).
1. toString() :
hashCode() :
For every object, JVM generates a unique number which is hashcode. It returns
distinct integers for distinct objects.
A common misconception about this method is that hashCode() method returns
the address of object, which is not correct.
Returns a hash value that is used to search object in a collection. JVM(Java Virtual
Machine) uses hashcode method while saving objects into hashing related data
structures like HashSet, HashMap, Hashtable etc. The main advantage of saving
objects based on hash code is that searching becomes easy.
int roll_no;
Student()
{
roll_no = last_roll;
last_roll++;
}
return roll_no;
}
/*public String toString()
{
return "Mystudent"+hashCode();
}
*/
public static void main(String args[])
{
Student s1 = new Student();
Student s2 = new Student();
// Below two statements are equivalent
System.out.println(s1);
System.out.println(s1.toString());
System.out.println(s2);
System.out.println(s2.toString());
}
}
Output :
Student@64
Student@64
Student@65
equals(Object obj) :
this method compare the reference addresses of two objects. if two objects
adresse are same then it return true otherwise it return false
example:
public class EqualDemo
{
public static void main(String[] args)
{
System.out.println(d1.equals(d2));
}
}
output: false
getClass() :
28
We can use this class object to get Class level information.i.e meta data of a class
Returns the class object of “this” object and used to get actual runtime class of
the object.
System.out.println(c.getName());
System.out.println(c.getModifiers());
System.out.println(c.hashCode());
}
Output:
2018699554
class classroom.GetclassDemo
classroom.GetclassDemo
1
1829164700
Note :After loading a .class file, JVM will create an object of the
type java.lang.Class in the Heap area. We can use this class object to get Class
level information. It is widely used in Reflection
finalize() method :
For example before destroying Servlet objects web container, always called finalize
method to perform clean-up activities of the session.
Note :finalize method is called just once on an object even though that object is
eligible for garbage collection multiple times.
t1 = null;
t2 = null;
Output:
2018699554
1311053135
30
clone() :
It returns a new object that is exactly the same as this object. For clone() method
refer Clone()
2. polymorphism
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism means many
forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and
method overriding.
Method Overloading: This allows us to have more than one method having the same
name, if the parameters of methods are different in number, sequence and data types of
parameters. We have already discussed Method overloading here:
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
Output:
30
60
33
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For
Example:
1. interface I{}
2. class A{}
3. class B extends A implements I{}
B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.
In this example, we are creating two classes Bike and Splendor. Splendor class extends
Bike class and overrides its run() method. We are calling the run method by the
reference variable of Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
1. class Bike{
2. void run()
3. {
4. System.out.println("running");
5. }
6. }
7. class Splendor extends Bike{
8. void run()
9. {
10.System.out.println("running safely with 60km");
11.}
12.
13. public static void main(String args[]){
14. Bike b = new Splendor();//upcasting
15. b.run();
16. }
17.}
Test it Now
Output:
Understanding Type
Let's understand the type of instance.
1. int data=30;
1. class Animal{}
2.
3. class Dog extends Animal
4. {
5. public static void main(String args[])
6. {
7. Dog d1=new Dog();
36
8. }
9. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.
If there is any private, final or static method in a class, there is static binding.
8. class Dog extends Animal{
9. void eat()
10.{
11.System.out.println("dog is eating...");}
12.
13. public static void main(String args[]){
14. Animal a=new Dog();
15. a.eat();
16. }
17.}
Test it Now
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.
In other words, 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.
2. The method must have the same parameter as in the parent class.
38
Let's understand the problem that we may face in the program if we don't use method
overriding.
1. //Java Program to demonstrate why we need method overriding
2. //Here, we are calling the method of parent class with child
3. //class object.
4. //Creating a parent class
5. class Vehicle
6. {
7. void run()
8. {
9. System.out.println("Vehicle is running with 40 km");
10.}
11.}
12.//Creating a child class
13.class Bike extends Vehicle
14.{
15. public static void main(String args[])
16.{
17. //creating an instance of child class
18. Bike obj = new Bike();
19. //calling the method with child class instance
20. obj.run();
21. }
22.}
Test it Now
Output:
The name and parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run()
6. {
7. System.out.println("Vehicle is running");
8. }
9. }
10.//Creating a child class
11.class Bike2 extends Vehicle
12.{
13. //defining the same method as in the parent class
14. void run()
15.{
16.System.out.println("Bike is running safely with 60 km");
17.}
18.
19. public static void main(String args[]){
20. Bike2 obj = new Bike2();//creating object
21. obj.run();//calling method
22. }
23.}
Test it Now
Output:
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
2. Interface (100%)
An abstract class outlines the methods but not necessarily implements all the methods.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It cannot be instantiated.
o It can have final methods which will force the subclass not to change the body of
the method.
Rules
1: when it is difficult or often unnecessary to implement all the methods in parent class.
In these cases, we can declare the parent class as abstract, which makes it a special
class which is not complete on its own.
A class derived from the abstract class must implement all those methods that are
declared as abstract in the parent class.
2: Abstract class cannot be instantiated which means you cannot create the object of it.
To use this class, you need to create another class that extends this class and provides
the implementation of abstract methods, then you can use the object of that child class
to call non-abstract methods of parent class as well as implemented methods(those
that were abstract in parent but implemented in child class).
3: If a child does not implement all the abstract methods of abstract parent class, then
the child class must need to be declared abstract as well.
Do you know? Since abstract class allows concrete methods as well, it does not
provide 100% abstraction. You can say that it provides partial abstraction. Abstraction
is a process where you show only “relevant” data and “hide” unnecessary details of an
object from the user.
Because these classes are incomplete, they have abstract methods that have no body
so if java allows you to create object of this class then if someone calls the abstract
method using that object then What would happen?
43
1. abstract class A{}
1. abstract void printStatus();//no method body and abstract
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. Bike obj = new Honda4();
13. obj.run();
14.}
15.}
Test it Now
44
running safely
Supported Abstract class can have both an A concrete class can only have
Methods abstract as well as concrete methods. concrete methods. Even a single
1
abstract method makes the class
abstract.
Instantiation Abstract class can not be instantiated Concrete class can be instantiated
2
using new keyword. using new keyword.
Abstract Abstract class may or may not have Concrete clas can not have an
3
method abstract methods. abstract method.
Final Abstract class can not be declared as Concrete class can be declared
4
a final class. final.
Keyword Abstract class declared using abstract Concrete class is not having
5 keyword. abstract keyword during
declaration.
Inheritance Abstract class can inherit another Interface can inherit only an
6 class using extends keyword and inteface.
implement an interface.
4. 1 Interfaces
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
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.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
46
4. // declare methods that abstract
5. // by default.
6. }
However, an interface is different from a class in several ways, including −
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces
In other words, Interface fields are public, static and final by default, and the methods
are public and abstract.
File: TestInterface2.java
47
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10.class TestInterface2{
11.public static void main(String[] args){
12.Bank b=new SBI();
13.System.out.println("ROI: "+b.rateOfInterest());
14.}}
Test it Now
Output:
ROI: 9.15
1. interface Printable{
2. void print();
48
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11.public static void main(String args[]){
12.A7 obj = new A7();
13.obj.print();
14.obj.show();
15. }
16.}
Test it Now
Output:Hello
Welcome
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10.public static void main(String args[]){
11.TestInterface3 obj = new TestInterface3();
49
12.obj.print();
13. }
14.}
Test it Now
Output:
Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class TestTnterface1, so there is no
ambiguity.
Interface inheritance
A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11.public static void main(String args[]){
12.TestInterface4 obj = new TestInterface4();
13.obj.print();
14.obj.show();
15. }
16.}
Test it Now
Output:
Hello
50
Welcome
File: TestInterfaceDefault.java
1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10.Drawable d=new Rectangle();
11.d.draw();
12.d.msg();
13.}}
Test it Now
Output:
drawing rectangle
default method
File: TestInterfaceStatic.java
1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
51
7. }
8.
9. class TestInterfaceStatic{
10.public static void main(String args[]){
11.Drawable d=new Rectangle();
12.d.draw();
13.System.out.println(Drawable.cube(3));
14.}}
Test it Now
Output:
drawing rectangle
27
1. //How Serializable interface is written?
2. public interface Serializable{
3. }
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
52
Supported A class can have both an Interface can have only abstract
1 Methods abstract as well as concrete methods. Java 8 onwards, it can have
methods. default as well as static methods.
Supported final, non-final, static and non- Only static and final variables are
3
Variables static variables supported. permitted.
Inheritance A class can inherit another Interface can inherit only an inteface.
6 class using extends keyword
and implement an interface.
Access A class can have any type of Interface can only have public
8
members like private, public. members.
9 Constructor A class can have constructor Interface can not have a constructor.
53
methods.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables.
variables.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
}
55
spd.topSpeed();
spd.topSpeed();
spd.topSpeed();
}
56
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
In java, an interface can extend another interface. When an interface wants to extend
another interface, it uses the keyword extends. The interface that extends another
interface has its own members and all the members defined in its parent interface too.
The class which implements a child interface needs to provide code for the methods defined
in both child and parent interfaces, otherwise, it needs to be defined as abstract class.
🔔 An interface can extend another interface.
🔔 An interface can not extend multiple interfaces.
🔔 An interface can implement neither an interface nor a class.
🔔 The class that implements child interface needs to provide code for all the methods
defined in both child and parent interfaces.
57
interface ParentInterface{
void parentMethod();
}
obj.childMethod();
obj.parentMethod();
}
58
Output:
5. inner classes
Java inner class or nested class is a class which is declared inside the class or
interface.
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
Additionally, it can access all the members of outer class including private data
members and methods.
Syntax
class OuterClass
{
//code
class InnerClass
{
//code
}
}
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
Type Description
Anonymous Inner A class created for implementing interface or extending class. Its
Class name is decided by the java compiler.
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11.}
Test it Now
61
Output:
data is 30
Output:
30
2. Interface
Output:
nice fruits
o Static nested class cannot access non-static (instance) data member or method.
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10.}
Test it Now
Output:
data is 30
In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because
nested class is static and static properties, methods or classes can be accessed without
object.
6. packages
Defination : 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.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
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
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
65
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
1. import package.*;
2. import package.classname;
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.
9. }
10.}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
67
a package has imported, we can refer to all the classes of that package using their
name directly.
The import statement must be after the package statement, and before any other
statement.
Using an import statement, we may import a specific class or all the classes from a
package.
🔔 Using one import statement, we may import only one package or a class.
68
🔔 Using an import statement, we can not import a class directly, but it must be a part
of a package.
Using an importing statement, we can import a specific class. The following syntax is
Syntax
import packageName.ClassName;
Let's look at an import statement to import a built-in package and Scanner class.
Example
package myPackage;
import java.util.Scanner;
int i = read.nextInt();
Using an importing statement, we can import all the classes of a package. To import all
the classes of the package, we use * symbol. The following syntax is employed to
Syntax
import packageName.*;
Example
package myPackage;
import java.util.*;
int i = read.nextInt();
it also importing all the classes like Scanner, Random, Stack, Vector, ArrayList,
🔔 The import statement imports only classes of the package, but not sub-packages and
its classes.
🔔 We may also import sub-packages by using a symbol '.' (dot) to separate parent
import java.util.*;