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

java CHAPTER 3 - Copy

The document covers key concepts of inheritance, interfaces, and packages in Java, emphasizing the importance of inheritance as a fundamental aspect of object-oriented programming (OOP). It explains various types of inheritance, including single, multilevel, and hierarchical inheritance, along with method and constructor overloading. Additionally, it discusses method overriding and the use of the 'super' keyword to access superclass methods and constructors.

Uploaded by

ps3639944
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

java CHAPTER 3 - Copy

The document covers key concepts of inheritance, interfaces, and packages in Java, emphasizing the importance of inheritance as a fundamental aspect of object-oriented programming (OOP). It explains various types of inheritance, including single, multilevel, and hierarchical inheritance, along with method and constructor overloading. Additionally, it discusses method overriding and the use of the 'super' keyword to access superclass methods and constructors.

Uploaded by

ps3639944
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Unit 3:

Inheritance , Interface
And Package
12 Marks
Inheritance in Java
• Inheritance is an important pillar of OOP.
• It is the mechanism in which one class is allow to inherit the
features(fields and methods) of another class.
Important terminology:
Super Class:
• The class whose features are inherited.(or a base class or a parent class).
Sub Class:
• The class that inherits the other class is known as sub class(or a derived
class, extended class, or child class).
• The subclass can add its own fields and methods in addition to the
superclass fields and methods.
Reusability:
• Inheritance supports “reusability”, i.e. when we create a new class and
there is already a class that includes some of the code that we want, we
can derive our new class from the existing class.
• By doing this, we are reusing the fields and methods of the existing
class.
Inheritance in Java
• Inheritance is an important pillar of OOP.
• It is the mechanism in which one class is allow to inherit the
features(fields and methods) of another class.

Important terminology:
• Super Class
• Sub Class
• Reusability

How to use inheritance in Java


• The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
class one {
Types of Inheritance: public void print_thakur()
{ System.out.println("Thakur"); }
Single Inheritance : }
In single inheritance, A class two extends one {
subclasses inherit the public void print_poly()
features of one superclass. {
System.out.println("Polytechnic");
}
}
public class SingleInheritanceExample {
public static void main(String[] args)
{
two t = new two();
t.print_thakur();
t.print_poly();
}
}
Multilevel Inheritance :
• When a derived class is inherited from another derived class.
• Here, class A serves as a base class for the derived

class B, which in turn serves as a base class for the derived class C.
class one {
public void print_thakur() public class Main
{ {
System.out.println("Thakur"); public static void main(String[] args)
{
}
three t = new three();
} t.print_thakur();
class two extends one { t.print_poly();
public void print_poly() t.print_kandivli();
{ }
}
System.out.println("Polytechnic");
}
}
class three extends two {
public void print_kandivli()
{
System.out.println("Kandivli");
}
}
Hierarchical Inheritance :
• In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one sub class.
• In below image, the class A serves as a base class for the
derived class B,C and D.
class three extends one
class one {
{ public void print_kandivli()
public void print_thakur() {
System.out.println("Kandivli");
{
}
System.out.println("Thakur"); }
}
} public class Main
{
class two extends one public static void main(String[] args)
{
{
three t = new three();
public void print_poly() t.print_thakur();
{ two w = new two();
w.print_poly();
System.out.println("Polytechnic"); t.print_kandivli();
} }
} }
Method Overloading in Java:
• Overloading allows different methods to have same name, but different
signatures where signature can differ by number of input parameters or type
of input parameters or both.
• Overloading is related to compile time (or static) polymorphism.
public class Sum
{
public int sum(int x, int y) { return (x + y); }
public int sum(int x, int y, int z) { return (x + y + z); }
public double sum(double x, double y) { return (x + y); }
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Constructors in Java
• Constructors are used to initialize the object’s data members.
When is a Constructor called ?
• Each time an object is created using new() keyword constructor is
invoked to assign initial values to the data members of the same class.
• Constructor is invoked at the time of object or instance creation.
class Thakur
{
Thakur() {}
}
Thakur obj = new Thakur(); //This statement calls above constructor.

Rules for writing Constructor:


I. Constructor(s) of a class must has same name as the class name in
which it resides.
II. A constructor in Java can not be abstract, final, static.
Constructor: How does a constructor work
• A constructor is similar to a public class Hello

method that initializes the {


String name;
newly created object when
Hello()
object of the class is created. {
• Constructor has the same System.out.println(“Constructor Called”);
name = “Thakur Polytechnic";
name as that of the class and
}
does not have any return type.
public static void main(String[] args)
• For example:
{
class Test {
Hello obj = new Hello();
Test() {
System.out.println(obj.name);
// constructor body
}
}
} }
Types of Constructors:
1. Default constructor
2. No-arg constructor
3. Parameterized constructor

Default constructor:
• If no constructor in a class, Java Type Default Value
compiler inserts a default boolean false

constructor into your code during byte 0

compilation and exists in .class file. short 0

• If any constructor is implemented then int 0

long 0L
their wont be any default constructor
char \u0000
from Java compiler in that class.
float 0.0f
• The default constructor initializes any
double 0.0d
uninitialized instance variables with object Reference null
No-arg constructor:
• Constructor with no arguments is known as no-arg constructor.

• The body can have any code unlike default constructor where the
body of the constructor is empty.
• If you write public Demo() { } in your class Demo it cannot be
called default constructor since you have written the code of it.
Example 1: class Demo
{
public Demo()
{
System.out.println(“No argument constructor");
}
public static void main(String args[])
{
Demo d=new Demo();
}
class Main
Parameterized {
Constructor: String languages;
A constructor that accepts Main(String lang)
one or more parameters are {
known as parameterized languages = lang;
constructors System.out.println(languages + " Programming

Language");
}
public static void main(String[] args) {

Main obj1 = new Main("Java");


Main obj2 = new Main("Python");
}
}
Constructor Overloading in Java
• Like methods, we can overload constructors for creating
objects in different ways.
• Compiler differentiates constructors on the basis of numbers
of parameters, types of the parameters and order of the
parameters.
When do we need Constructor Overloading?
Sometimes there is a need of initializing an object in different
ways. This can be done using constructor overloading.
class Box {
double width, height, depth;
Box(double w, double h, double d) { width = w; height = h; depth =
d; }
Box() { width = height = depth = 0; }
Box(double len) { width = height = depth = len; }
double volume() { return width * height * depth; }
}
public class Test {
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
System.out.println(" Volume of mybox1 is " + mybox1.volume());
System.out.println(" Volume of mybox2 is " + mybox2.volume());
System.out.println(" Volume of mycube is " + mycube.volume());
}
}
class Thakur
{
Thakur() { System.out.println("Constructor with zero argument"); }
Thakur(String name)
{ System.out.println("Constructor with one argument " + name); }
Thakur(String name, int age)
{
System.out.println("Constructor with two arguments :" + name + " "+ age);
}
}
class Poly
{
public static void main(String[] args) {
Thakur t1=new Thakur();
Thakur t2 = new Thakur("Yash");
Thakur t3 = new Thakur("Yashvi", 2);
}
}
Method Overloading in Java :
• Method Overloading is a feature that allows a class to have more than one
method having the same name, with different argument lists.
• It is similar to constructor overloading, that allows a class to have more
than one constructor having different argument lists.
• For example the argument list of a method add(int a, int b) having two
parameters is different from the argument list of the method add(int a, int
b, int c) having three parameters.

Three ways to overload a method:


• The argument lists of the methods must differ in either of these:
1. Number of parameters:
For example: add(int, int), add(int, int, int)
2. Data type of parameters:
For example: add(int, int), add(int, float)
3. Sequence of Data type of parameters.
For example: add(int, float) add(float, int)
class Adder
{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
double add(double a,double b){return a+b;}
}
class MethodOverloadingExample
{
public static void main(String[] args)
{
Adder A= new Adder();
System.out.println(A.add(10,20));
System.out.println(A.add(10.1,20.2));
System.out.println(A.add(10,20,30));
}
}
Method Overriding in Java
• Overriding is a feature that allows a subclass to provide
implementation of a method that is already provided by one of its
super-classes.
• When a method in a subclass and superclass has the same signature
and same return type, then we say method in subclass overrides
method in super-class.
• Method overriding is one of the way by which java achieve Run
Time Polymorphism.
• The version of a method that is executed will be determined by the
object that is used to invoke it.
• If an object of a parent class is used to invoke the method, then
parent class method will get executed, but if an object of the
subclass is used to invoke the method, then child class method will
execute.
class Base
{
public void show()
{
System.out.println("Base Class");
}
}
class Derived extends Base
{
public void show()
{
System.out.println("Derived Class");
}
public static void main( String args[])
{
Derived d = new Derived();
d.show();
}
}
Advantage of method overriding
• The class can give its own specific implementation to a inherited
method without even modifying the parent class code.
• This is helpful when a class has several child classes, so if a child
class needs to use the parent class method, it can use it and the other
classes that want to have different implementation can use
overriding feature to make changes without touching the parent
class code.
Method Overriding and Dynamic Method Dispatch:
• Method Overriding is an example of runtime polymorphism.
• When a parent class reference points to the child class object then
overridden method gets called at runtime, because during method
call, which method (parent class or child class) is to be executed is
determined by the type of object.
• The process that decides which method (parent class or child class)
to call is resolved at runtime is known as dynamic method
dispatch.
class ABC{
public void disp() { System.out.println("disp() in parent class"); }
}
class Demo extends ABC
{
public void disp() { System.out.println("disp() in Child class"); }
public void newMethod()
{
System.out.println("new method of child class");
}
public static void main( String args[])
{
ABC obj = new ABC(); // Reference of ABC points to object of ABC class.
obj.disp();
ABC obj2 = new Demo(); // Reference of ABC points to object of Demo class.
obj2.disp();
}
}
class Parent {
void show() { System.out.println("Parent's show()"); }
}
class Child extends Parent {
void show() { System.out.println("Child's show()"); }
}
class Main {
public static void main(String[] args)
{
// If Parent type reference refers Parent object, then Parent's show is called
Parent obj1 = new Parent();
obj1.show();
// If a Parent type reference refers to a Child object Child's show() is called. This
is called RUN TIME POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}
class Vehicle {
Super Keyword in Java int maxSpeed = 120;
1. Use of super with variables: }
class Car extends Vehicle {
• When a derived class and base class
int maxSpeed = 180;
has data members with same name. void display()
• In example, both base class and {
subclass have a member maxSpeed. System.out.println("Maximum Speed: "
+
We could access maxSpeed of base super.maxSpeed);
class in subclass using super }
keyword. }
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
class Person {
2. Use of super with methods:
void message() {
• Whenever a parent and child class have System.out.println(“Person class");
same named methods then to resolve }
ambiguity we use super keyword. }
class Student extends Person {
• In example , if we only call message()
void message() {
then, the current class message() will System.out.println(“Student class");
invoke but with the use of super }
void display() { super.message(); }
keyword, message() method of
}
superclass will invoke. class Test {
public static void main(String args[])
{
Student s = new Student();
s.display();
}
}
3. Use of super with constructors: class Person {
Person() {
• super keyword can also be used to
System.out.println("Person:Constructor")
access the parent class constructor. ;
}
• ‘Super’ can call both parametric as }
class Student extends Person{
well as non parametric
Student() {
constructors. super();
System.out.println("Student:Constructor");
• In example, superclass constructor }
}
is called using keyword ‘super’ via
class Test{
subclass constructor. public static void main(String[] args)
{
Student s = new Student();
}
}
Other Important points:
• Call to super() must be first statement in Derived(Student)
Class constructor.

• If a constructor does not explicitly invoke a superclass


constructor, the Java compiler automatically inserts a call to
the no-argument constructor of the superclass.
Inheritance and constructors in Java
• In Java, constructor of base class with no argument gets automatically called
in derived class constructor.
For example:
class Base
{
Base() { System.out.println("Base Class Constructor Called "); }
}
class Derived extends Base
{
Derived() { System.out.println("Derived Class Constructor Called "); }
}
public class Main
{
public static void main(String[] args)
{
Derived d = new Derived();
}
• If we want to call parameterized contructor of base class, then we can call it using
super().
• The point to note is base class constructor call must be the first line in derived class
constructor.
• For example, in the following program, super(x) is first line
derived class constructor.
class Base { int x;
Base(int x1) { x = x1; }
}
class Derived extends Base {
int y;
Derived(int x1, int y1) { super(x1); y = y1; }
void Display() { System.out.println("x = "+x+", y = "+y); }
}
public class Main {
public static void main(String[] args)
{
Derived d = new Derived(10, 20);
d.Display();
}
}
final keyword in java

• final keyword is used in different contexts. First of all, final is


a non-access modifier applicable only to a variable, a
method or a class.

• Following are different contexts where final is used.


Final variables
• When a variable is declared with final keyword, its value can’t
be modified, essentially, a constant.
• This also means that you must initialize a final variable.
• Example:
final int THRESHOLD = 5;
When to use a final variable :
• The only difference between a normal variable and a final
variable is that we can re-assign value to a normal variable but
we cannot change the value of a final variable once assigned.

• Hence final variables must be used only for the values that we
want to remain constant throughout the execution of program.
A final variable cannot be reassign, doing it will throw compile-time error.
class TP
{
final int CAPACITY = 4;
public static void main(String args[])
{
CAPACITY = 5; // throw compile-time error
}
}
Output
Compiler Error: cannot assign a value to final variable CAPACITY
Final methods: Method declared with final keyword is a final method.
• A final method cannot be overridden.
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1() // COMPILE-ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
Final classes
• When a class is declared with final keyword, it is called a final
class.

• A final class cannot be extended(inherited).


final class A
{
// methods and fields
}
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}
Abstract Class in Java:
• A class declared using “abstract” keyword is known as abstract class.
• In Java, abstraction is achieved using Abstract classes and interfaces.

Rules:
1. It can have abstract methods(methods without body) as well as
concrete methods (regular methods with body).
2. A normal class(non-abstract class) cannot have abstract methods.
3. We can not create object of it abstract class as these classes are
incomplete, they have abstract methods that have no body so java wont
allows you to create object of abstract class.
4. It can have final methods.
5. It can have constructor and static methods also.
Why we need an abstract class?
• Consider a class Shape and has a calculateArea() method for this class.
• As right now for shape - we don't know the implementation for the
calculateArea() method.
• If the shape is circle then its implementation will be for calculating area
for shape circle or if the shape is triangle then implementation will be for
calculating area for Shape Triangle..
• So for class Shape the calculateArea() method will be an abstract
(without implementation) and which ever concrete class will extend this
class, needs to provide implementation for this method.
abstract class Shape { public abstract void calculateArea(); }
class Rectangle extends Shape {
public void calculateArea() {
int length=4, breadth=3;
System.out.println("Area=:"+length * breadth);
}
}
class Circle extends Shape {
public void calculateArea() { int radius=3;
System.out.println("Area=:"+3.14*radius*radius);
}
}
class Triangle extends Shape {
public void calculateArea() { int length=2, height=3;
System.out.println("Area=:"+0.5*height*length);
}
}
Abstract method in Java
Rules:
1. Abstract methods don’t have body, they just have method signature.
2. If a class has an abstract method it should be declared abstract, the vice
versa is not true, which means an abstract class doesn’t need to have an
abstract method compulsory.
3. If a regular class extends an abstract class, then the class must have to
implement all the abstract methods of abstract parent class or it has to
be declared abstract as well.
Java : Static Block, Methods and Variables:
• Static keyword can be used with variable, method and block.
• Static members belong to the class instead of a specific
instance, this means you can access it without object.
Static Block:
• Static block is used for initializing the static variables.
• This block gets executed when the class is loaded in the memory.
• Example :
class StaticBlockExample
{
static int num;
static String mystr;
static { num = 97;
mystr = “Thakur Polytechnic";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
Java Static Variables:
• Static variables are also known as Class Variables.
• A static variable is common to all the instances (or objects) of the class
because it is a class level variable.
• Means, a single copy of static variable is created and shared among all
the instances (or objects) of the class.
• Static variables can be accessed directly in static and non-static
methods.
• Memory allocation for such variables only happens once when the
class is loaded in the memory.
Example 1: Static variables accessed directly in Static and non static method
class StaticVariableExample
{
static int var1;
static String var2;
void disp()
{
System.out.println("Var1 is: "+var1);
System.out.println("Var2 is: "+var2);
}
public static void main(String args[])
{
StaticVariableExample s = new StaticVariableExample();
s.disp();
}
}
Java Static Methods:
• Static Methods can access static variables and static methods without
using object of the class.
• Static methods can be accessed directly in static and non-static methods.
Syntax: static return_type method_name();

Example1: static method main is accessing static variables without object


class StaticMethodExample1
{
static int i = 10;
static String s = “tpolymumbai";
public static void main(String args[])
{
System.out.println("i:"+i);
System.out.println("s:"+s);
}
}
Interface in java
• Abstract class which is used for achieving partial abstraction.
• An interface is used for full abstraction.
• Abstraction is a process where you show only “relevant” data and
“hide” unnecessary details of an object from the user.
• Interface looks like a class but it is not a class.
• An interface can have methods and variables just like the class but the
methods declared in interface are by default abstract (without body).
• The class that implements interface must define all the methods of that
interface.
• Also, the variables declared in an interface are public, static & final by
default, and should be initialized as final.
Why do we use interface ?
• It is used to achieve total abstraction.
• Since java does not support multiple inheritance in case of class, but by
using interface we can achieve multiple inheritance.
Syntax: interface <interface_name>
{
// declare constant fields
// declare methods that abstract by default.
}

• The Java compiler adds public and abstract keywords before the
interface method.
• Also, it adds public, static and final keywords before data members.
The relationship between classes and interfaces

• A class extends another class.


• An interface extends another interface.
• A class implements an interface.
Similarities between class and interface:
• Both can contain any number of variables and methods (class
methods have implementation code whereas the interface
methods can only have declarations)
• Both can be written in a file with .java extension, with the
name of the interface/class matching the name of the file.
• The byte code of both appears in a .class file.
• Both can be inherited using Inheritance (extends keyword for
classes and implements keyword for interfaces)
Difference between Class and Interface:
Sr. Key Class Interface
No.

1 Basic A class is instantiated to An interface can never be


create objects. instantiated.
Supported A class can have both an Interface can have only abstract
2 Methods abstract as well as concrete methods.
methods.

3 Multiple Multiple Inheritance is not Interface supports Multiple


Inheritance supported. Inheritance.
Supported final, non-final, static and Only static and final variables
4 Variables non-static variables are permitted.
supported.
Sr. Key Class Interface
No.

Implement A class can implement an Interface can not implement an


5
ation interface. interface, it can extend an
interface.
6 Keyword Declared using class Declared using interface
keyword. keyword.

Inheritance A class can be inherited


Interface can only be
7
using extends keyword.implemented using implements
keyword.
Access Class members can be Interface only has public
8
private, public, protected members.
etc
Constructo A class can have Interface can not have a
9 r constructor methods. constructor.
Example 1:
interface printable
{
void print();
}
class InterfaceExample implements printable {
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
InterfaceExample obj = new InterfaceExample();
obj.print();
}
}
• Interface variables must be initialized at the time of declaration
otherwise compiler will throw an error.
• Example: interface Try
{
int x; //Compile-time error
}
____________________________________________________________
_
• Variables declared in interface cant be modified as by default, they are
public, static and final.
• Example:
Interface Try { int x=10; }
class Sample implements Try {
public static void main(String args[])
{
x=20; //compile time error
}
Multiple inheritance Using interface:
• Multiple inheritance is not supported in the case of class because of
ambiguity.
• However, it is supported in case of an interface because there is no
ambiguity.
• It is because its implementation is provided by the implementation
class.
• If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.
interface Printable { void print(); }
interface Showable { void show(); }
class InterfaceExample1 implements Printable, Showable
{
public void print() { System.out.println("Hello"); }
public void show() { System.out.println("Welcome"); }
public static void main(String args[])
{
InterfaceExample1 obj = new InterfaceExample1();
obj.print();
obj.show();
}
}
interface Printable { void print(); }
interface Showable { void print(); }
class TestInterface3 implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Interface References:
• If a class implements an interface and provide body to its methods,
then object of the that class can be stored by the reference variable
of the interface.
• But, using this you can only access the methods of the interface
only, if you try to access the methods of the class which
implements that interface then compile time error is generated.
interface MyInterface { public void display(); }
public class InterfaceExample implements MyInterface
{
public void display() { System.out.println(“Display Method"); }
public void show() { System.out.println(“Sow method"); }
public static void main(String args[])
{
MyInterface obj = new InterfaceExample();
obj.display();
obj.show(); //error: cannot find symbol obj.show();
}
}
Nested/ Inner Interfaces:
• An interface which is declared inside another interface or class is called
nested interface.
• The main purpose of nested interfaces is to group related interfaces
together.
• The nested interfaces can be called by using outer class or outer interface
name followed by dot( . ), followed by the interface name.
Rules for nested interface:
• A nested interface declared within an interface must be public.
• A nested interface declared within a class can have any access modifier.
• A nested interface is by default static.
Example 1: Nested interface declared inside another interface
interface MyInterfaceA
{
void display();
interface MyInterfaceB { void myMethod(); }
}
class NestedInterface implements MyInterfaceA.MyInterfaceB
{
public void myMethod()
{
System.out.println("Nested interface method");
}
public static void main(String args[])
{
MyInterfaceA.MyInterfaceB obj=new NestedInterface();
obj.myMethod();
}
}
Example 2: Nested interface declared inside a class
class MyClass
{
interface MyInterfaceB { void myMethod(); }
}
class NestedInterfaceClass implements MyClass.MyInterfaceB
{
public void myMethod()
{
System.out.println("Nested interface method");
}
public static void main(String args[])
{
MyClass.MyInterfaceB obj=new NestedInterfaceClass();
obj.myMethod();
}
}
Java Package:
• A java package is a group of similar types of classes, interfaces and
sub-packages.
Types of packages in Java
• As mentioned in the beginning of this guide that we have two types of
packages in java.
1) User defined package: The package we create is called user-
defined package.
2) Built-in package:
Built-in Java Packages:
1. java.lang: Contains language support classes(e.g classes which defines
primitive data types, math operations).
2. java.io: Contains classed for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like
Linked List, Dictionary and support for Date / Time operations.
4. java.applet: Contains classes for creating Applets.
5. java.awt: Contain classes for implementing the components for
graphical user interfaces (like button , ;menus etc).
6. java.net: Contain classes for supporting networking operations.
Advantages of using a package in Java
• Reusability: Using packages, we create classes inside a package and
whenever you need to perform that same task, just import that package
and use the class.

• Better Organization: Again, in large java projects where we have


several hundreds of classes, it is always required to group the similar
types of classes in a meaningful package name so that you can organize
your project better and when you need something you can quickly locate
it and use it, which improves the efficiency.

• Name Conflicts: We can define two classes with the same name in
different packages so to avoid name collision, we can use packages
For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee

• Packages can be considered as data encapsulation (or data-hiding).


Additional points about package:
• Package statement must be first statement in the program even
before the import statement.
• A package is always defined as a separate folder having the
same name as the package name.
• Store all the classes in that package folder.
• All classes of the package which we wish to access outside the
package must be declared public.
• All classes within the package must have the package
statement as its first line.
• All classes of the package must be compiled before use.
Accessing classes inside a package
• Consider following two statements :
1. import java.util.vector;
2. import java.util.*;
3.import package.*;
4. import package.classname;
• First Statement imports Vector class from util package in java.
• Second statement imports all the classes from util package.
• Third statement imports all the classes and interfaces of this package
will be accessible but not sub packages.
• Forth statement, the class name is used as there may be two packages
with same class name.
• For example in below code both packages have date class so using
fully qualified name to avoid conflict
import java.util.Date;
import my.packag.Date;
User-defined packages
• These are the packages that are defined by the user. First we
create a directory myPackage (name should be same as the name
of the package). Then create the MyClass inside the directory
with the first statement being the package names.
• // Name of the package must be same as the directory under
which this file is saved
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{ // Initializing the String variable with a value
String name = “Thakur";
MyClass obj = new MyClass();
obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage
directory since it is a part of the package.
Using Static Import
• Static import allows members ( fields and methods ) defined in a class
as public static to be used in Java code without specifying the class in
which the field is defined.
Following program demonstrates static import :
// Note static keyword after import.
import static java.lang.System.*;

class StaticImportDemo
{
public static void main(String args[])
{
// We don't need to use 'System.out' as imported using static.
out.println("Thakur Polytechnic");
}
}
Thakur Polytechnic

You might also like