Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Java Unit II Notes.docx

The document provides an overview of inheritance, interfaces, and packages in Java, detailing types of inheritance such as single, multi-level, and hierarchical inheritance, along with examples. It explains method overriding, the use of the final keyword, abstract methods and classes, and the concept of interfaces, including their implementation and extension. The document serves as a comprehensive guide for understanding these fundamental object-oriented programming concepts in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Unit II Notes.docx

The document provides an overview of inheritance, interfaces, and packages in Java, detailing types of inheritance such as single, multi-level, and hierarchical inheritance, along with examples. It explains method overriding, the use of the final keyword, abstract methods and classes, and the concept of interfaces, including their implementation and extension. The document serves as a comprehensive guide for understanding these fundamental object-oriented programming concepts in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

=====================================

UNIT-II: Inheritance, Interface and Packages


=====================================
Inheritance:
- The process of creating new class from old class is known as Inheritance.
- The mechanism of acquiring the properties of old class into the new class
class is known as Inheritance.
- The newly created class is known as Subclass/child/derived class.
- Old class is known as Super class/Parent class/Base class.
- Inheritance will help us to achieve reusability feature.
- Because of Inheritance, our development time will get save and it will also
impact on the project cost.

- Types of Inheritance:
1) Single Inheritance
2) Multi-level Inheritance
3) Multiple Inheritance
4) Hierarchical Inheritance
5) Hybrid Inheritance
- We use following syntax for creating the new class from old class. class
DerivedClassName extends BaseClassName
{
//body of Derived Class
}

1) Single Inheritance:
- This is one of the types of inheritance.
- To create new class from only one base class is known as single
inheritance.
- Syntax:

class DerivedClassName extends BaseClassName


{
//body of Derived Class
}
- Program:
//Single Inheritance import java.util.*; class Student
{
int rollno;
String name;
void get_stud_info()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Roll No:");
rollno=sc.nextInt();
System.out.println("Enter Student Name:"); name=sc.next();
}
void disp_stud_info()
{
System.out.println("Student ROll No:"+rollno);
System.out.println("Student Name:"+name);
}
}

class Test extends Student


{
int marks1,marks2;
void get_stud_marks()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Test-1 Marks:");
marks1=sc.nextInt();
System.out.println("Enter Student Test-2 Marks:");
marks2=sc.nextInt();
}
void disp_stud_marks()
{
System.out.println("Test-1 Marks:"+marks1);
System.out.println("Test-2 Marks:"+marks2);
}
}
class SingleInheritanceDemo
{
public static void main(String args[])
{
Test t1=new Test();
t1.get_stud_info();
t1.get_stud_marks();
System.out.println("*******STUDENT INFORMATION
SYSTEM********");
t1.disp_stud_info();
t1.disp_stud_marks();
}
}
/*
Enter Student Roll No:
1010
Enter Student Name:
James
Enter Student Test-1 Marks:
89
Enter Student Test-2 Marks:
78
*******STUDENT INFORMATION SYSTEM******** Student ROll
No:1010
Student Name:James Test-1 Marks:89 Test-2 Marks:78
*/

2) Multi-level Inheritance:
- The mechanism of deriving the class from another derived class is known
as multi-level inheritance.
- To create new class from another derived class is known as multi-level
inheritance.
- It is one of the types of inheritance.
- Syntax:
class BaseClass1
{
//body of BaseClass1 Class
}
class DerivedClass1 extends BaseClass1
{
//body of DerivedClass1
}
class DerivedClass2 extends DerivedClass1
{
//body of DerivedClass2
}
-Example
//Multi-level Inheritance
import java.util.*;
class Student
{
int rollno;
String name;
void get_stud_info()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Roll No:");
rollno=sc.nextInt();
System.out.println("Enter Student Name:");
name=sc.next();
}
void disp_stud_info()
{
System.out.println("Student ROll No:"+rollno);
System.out.println("Student Name:"+name);
}
}
class Test extends Student
{
int marks1,marks2;
void get_stud_marks()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Test-1 Marks:");
marks1=sc.nextInt();
System.out.println("Enter Student Test-2 Marks:");
marks2=sc.nextInt();
}
void disp_stud_marks()
{
System.out.println("Test-1 Marks:"+marks1);
System.out.println("Test-2 Marks:"+marks2);
}
}
class Result extends Test
{
int total_marks;
void get_total_marks()
{
total_marks=marks1+marks2;
}
void disp_total_marks()
{
System.out.println("Total Marks:"+total_marks);
}
}
class MultilevelInheritanceDemo
{
public static void main(String args[])
{
Result t1=new Result();
t1.get_stud_info();
t1.get_stud_marks();
t1.get_total_marks();

System.out.println("*******STUDENT INFORMATION SYSTEM********");

t1.disp_stud_info();
t1.disp_stud_marks();
t1.disp_total_marks();
}
}
/*
Enter Student Roll No:
1010
Enter Student Name:
James
Enter Student Test-1 Marks: 78
Enter Student Test-2 Marks:
90
*******STUDENT INFORMATION SYSTEM********
Student ROll No:1010
Student Name:James
Test-1 Marks:78
Test-2 Marks:90
Total Marks:168
*/
3) Hierarchical Inheritance:
- To create more than one derived class from only one base class is known as
Hierarchical inheritance.
- It is one of the types of inheritance.
- We use following syntax for creating the new class from old class.

class DerivedClassName extends BaseClassName


{
//body of Derived Class
}

- Program:
//Hierarchical Inheritance
import java.util.*;

class Student {
int rollno;
String name;

void get_stud_info() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Student Roll No:");
rollno = sc.nextInt();
System.out.println("Enter Student Name:");
name = sc.next();
}

void disp_stud_info() {
System.out.println("Student Roll No: " + rollno);
System.out.println("Student Name: " + name);
}
}

// First child class


class Test extends Student {
int marks1, marks2;

void get_stud_marks() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Student Test-1 Marks:");
marks1 = sc.nextInt();
System.out.println("Enter Student Test-2 Marks:");
marks2 = sc.nextInt();
}

void disp_stud_marks() {
System.out.println("Test-1 Marks: " + marks1);
System.out.println("Test-2 Marks: " + marks2);
}
}

// Second child class


class Sport extends Student {
float sport_wt;

void get_sport_info() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sport Weightage:");
sport_wt = sc.nextFloat();
}

void disp_sport_info() {
System.out.println("Sport Weightage: " + sport_wt);
}
}

// Main class to demonstrate hierarchical inheritance


class HierarchicalInheritanceDemo {
public static void main(String args[]) {
Test t1 = new Test();
System.out.println("\n***** Test Class Implementation *****");
t1.get_stud_info();
t1.get_stud_marks();
t1.disp_stud_info();
t1.disp_stud_marks();

Sport s1 = new Sport();


System.out.println("\n***** Sport Class Implementation *****");
s1.get_stud_info();
s1.get_sport_info();
s1.disp_stud_info();
s1.disp_sport_info();
}
}
/*
***** Test Class Implementation *****
Enter Student Roll No: 1010
Enter Student Name: James
Enter Student Test-1 Marks: 89
Enter Student Test-2 Marks: 78

Student Roll No: 1010


Student Name: James
Test-1 Marks: 89
Test-2 Marks: 78

***** Sport Class Implementation *****


Enter Student Roll No: 2020
Enter Student Name: Alice
Enter Sport Weightage: 9.5

Student Roll No: 2020


Student Name: Alice
Sport Weightage: 9.5 */
Method Overriding:
====================
- Suppose, base class and derived class method names are same.
- When base class method derived in derived class then it got overide.- It
means base class method overriden by derived class method.
- To call overriden method, we can use super keyword.
- We use syntax for calling hidden method: super.methodName();
- Program:
//Method overriding and use of super keyword class Base
class Base {
void display() {
System.out.println("display() method of Base class");
}
}

class Derived extends Base {


void display() {
super.display(); // Calling Base class method
System.out.println("display() method of Derived class");
}
}

class MethodOverridingDemo {
public static void main(String args[]) {
Derived d1 = new Derived();
d1.display(); // Calls overridden method
}
}

/*
display() method of Base class
display() method of Derived class
*/
====================================
How to invoke Base class Constructor
=====================================
- Base class constructor should not inherit in its sub class.
- Suppose, base class contain constructor then how we can call that
constructor.
- In this case, we can super keyword.
- super keyword should be the first line of derived class constructor body.
- Syntax-
super(); // Calls base class default constructor
OR
super(argument_list); // Calls base class parameterized constructor

- Program1:

class Base {
Base() {
System.out.println("Base class constructor called...!!!");
}
}

class Derived extends Base {


Derived() {
super(); // Calling base class constructor
System.out.println("Derived class constructor called...!!!");
}
}

public class InvokeBaseClassConstructor {


public static void main(String args[]) {
Derived d1 = new Derived();
}
}

/*
Base class constructor called...!!!
Derived class constructor called...!!!
*/
-Program2:
//use of super keyword for calling base class parameterized constructor.
class Base {
int x;

Base(int m) {
x = m;
System.out.println("Base class constructor called.. m = " + m);
}
}

class Derived extends Base {


int y;

Derived(int p, int q) {
super(p); // Calling Base class constructor
y = q;
System.out.println("Derived class constructor called.. q = " + q);
}
}

class InvokeBaseClassConstructor1 {
public static void main(String args[]) {
Derived d1 = new Derived(100, 200);
}
}
/*
Base class constructor called..x=100
Derived class constructor called..y=200
*/
============
Final Keyword
============
- final is a predefined keyword.
- Following are the uses of final keyword:

---------------------
Final Variable
---------------------
1) To make constant variable:
- If we declare the variable using final keyword then that variable become
Constantin java.
- Constant variable means, once it is created then we cannot change its value
later.
- Constant us a variable which cannot change its value during the execution
of program.
- Example:
class finalKeywordDemo
{
public static void main(String args[])
{
final float PI=3.14f; //constant variable
int radius=2;
float area;
area=(PI*radius*radius);
System.out.println("Area of Circle="+area);
}
}
/*
Area of Circle=12.56
*/
---------------------
Final Method
---------------------
2) To avoid method overriding:
- Suppose, base class method name and derived class method name are same
then base class method overridden by derived class method.
- If we want to avoid method overriding then we can use final keyword
before the base class method declaration.
- Example:
//To avoid method overriding
class Base
{
final void display()
{
System.out.println("display method of base class");
}
}
class Derived extends Base
{
void display()
{
System.out.println("display method of derived class");
}
}
class AvoidMethodOverriding
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
}
}
/*
error: display() in Derived cannot override display() in Base
void display() {
^
overridden method is final
1 error*/

---------------------
Final Class
---------------------
3) To avoid inheritance:
- To avoid inheritance then we can declare the base class using final
keyword.
- If we declare base class using final keyword then we cannot create subclass
from it.
- Example: //To avoid method overriding final
class Base
{
void display()
{
System.out.println("display method of base class");
}
}
class Derived extends Base
{
void show()
{
System.out.println("show method of derived class");
}
}
class AvoidInheritance
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
d1.show();
}
}
/*
AvoidInheritance.java:9: error: cannot inherit from final Base class Derived
extends Base */

Abstract Methods and Classes


• Abstract Methods: -
o Abstract method is such a method of which on the declaration is there in
the base class and we have to define it in derived class.
o It can never be final and static.
o Abstract keyword is used to while declaring abstract method but not at
the time of defining it
• Abstract Classes: -
o The base class in which abstract methods are declared is called as
abstract class.
o Abstract classes can have members, variables, constructors,
normal methods.

Example
// Abstract class
abstract class Animal {
// Abstract method (no implementation)
abstract void sound();

// Regular method
void sleep() {
System.out.println("This animal is sleeping.");
}
}

// Subclass (inherited from Animal)


class Dog extends Animal {
// Providing implementation for the abstract method
void sound() {
System.out.println("The dog barks.");
}
}

class Main {
public static void main(String[] args) {
// Creating an object of the subclass
Dog myDog = new Dog();

// Calling the implemented abstract method


myDog.sound();

// Calling the regular method from the abstract class


myDog.sleep();
}
}
Output
The dog barks.
This animal is sleeping.
o Any class which inherits and abstract class must implement all the
abstract methods which are declared by abstract class
Interface:
• An interface is similar to the class.
• Interface is a collection of abstract methods and final static variables.
• Interface is used to achieve the multiple inheritance concepts in Java.
• All the abstract methods of the interface need to be defined in its sub class.
• An Interface does not contain any constructors.
• We cannot create the objects of an interface.
• All of the methods of the Interface are by default abstract.
• All of the variables of the Interface are by default static, final.
• An interface is not extends the properties of the class but it is implemented
by a class.
• One interface can extend the multiple interfaces.
Syntax:
interface Interface_Name
{
datatype final_variable_name1=value1; //Any number of final,static variables
---
---
returntype method_name(parameter_list); //Any number of abstract method
declarations
---
---
}

Example:

interface Area
{
float PI=3.14f;
void compute(int x,int y);
}

The java compiler adds public and abstract keywords before the interface
method. It adds public, static and final keywords before data members.
Implementing interface:
• Class implements an interface.
• The class uses the implements keyword for implementing the interface.
• Class is responsible for implementing the abstract methods of the interface.
Syntax:
class class_name implements interface_name
{
//body of class
}
Example:
interface Area
{
float PI=3.14f;
void compute(int r);
}
class Circle implements Area
{
public void compute(int r)
{
System.out.println(“Area of Circle=”+(PI*r*r));
}
public static void main(String args[]) {
Circle c1=new Circle();
c1.compute(10);
}
}

Output:
Area of Circle=314.0

Extending interface:
• One interface can extend another interface same way that a class can extend
another class.
• The extends keyword is used to extend an interface.
• In this case sub interface inherits the properties of super interface, but it
will not define the methods of the super interface.
• Java class does not extend more than one class because java does not
support to the multiple inheritance.
• But interface is not a class, it can extend two or more interfaces, they are
separated by the commas.
Syntax:
interface sub_interface extends super_interface
{ //body of sub interface }

Example:
interface Abc
I {am from Abc interface:
void display();
I am from Xyz interface:
} interface Xyz extends Abc
{
void show();
}
class Mnp implements Xyz
{
public void display()
{
System.out.println(“I am from Abc interface:”);
}
public void show()
{
System.out.println(“I am from Xyz interface:”);
}
public static void main(String args[])
{
Mnp m1=new Mnp();
m1.display();
m1.show();
}
}

Output:

Understand the relationship between classes and interfaces:

class extends class class implements interface interface extends interface interface extends class
Multiple inheritance in Java by using interface:

• To inherit the properties of more than one base class into sub class is known
as multiple inheritances.
• In multiple inheritance we can combine the features of more than one
existing class into new class.
• Below diagram shows the multiple inheritance concepts:

• Java classes cannot have more than one super class. But in most of the real
time application multiple inheritances is required. So java provides an
alternative approach is known as interface.
• Interface is a collection of static final variables and abstract methods. It is
used to achieve the multiple inheritance in Java.
• If a class implements multiple interfaces, or an interface extends multiple
interfaces i.e. known as multiple inheritance in Java.

• Below diagram shows, how to achieve the multiple inheritance in Java


language:
• In first diagram, class implementing more than one interface and in second
diagram interface extending more than one interfaces to achieve the multiple
inheritance in Java.
Example:
interface Abc
{
void display();
}
interface Xyz
{
void show();
}
class Mnp implements Abc,Xyz
{
public void display()
{
System.out.println(“I am from Abc interface:”);
}
public void show()
{
System.out.println(“I am from Xyz interface:”);
}
public static void main(String args[]) {
Mnp m1=new Mnp();
m1.display();
m1.show();
}
}
Output:
I am from Abc interface:
I am from Xyz interface:

• Difference between Abstract class and Interface:


Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
nonabstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables. variables.

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

5) The abstract keyword is used The interface keyword is used to


to declare abstract class. declare Interface

6) Abstract class can extend another Java An interface can extend another Java
class and implements interface only.
multiple interfaces.
7) Abstract class achieves partial Interface achieves fully abstraction.
abstraction.

8) abstract class Abc 8) interface drawable


{ {
abstract void draw(); void draw();
} }

• Difference between class and Interface:


Class Interface
1) We can create objects from We cannot create the objects from
class. interface.
2) The members of a class can be private, The members of an interface are always
public or protected. public.
3) Class contains abstract or non- Interface has only abstract methods.
abstract methods.
4) Class can contain methods definitions. Interface can contain only declaration of
methods without body.
5) The class keyword is used to declare The interface keyword is used to declare
class. interface.
6) A class can implement multiple An interface can extend multiple
interfaces but cannot extend multiple interfaces but can extend only one class.
classes.

7) Constructor present in class Constructor not present in class

8) Example:
Example: interface Xyz
class Abc {
{ void draw();
Void draw(); }
}

Java Package:
• Putting classes and interfaces together is known as Package.
• Package is a collection of similar types of classes and interfaces.
• Packages are acts as container for the classes and interfaces.
• We can achieve the reusability features of Java by using Inheritance and
packages.
• Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces.
• A package is a collection of related classes. It helps Organize your classes
into a folder structure and make it easy to locate and use them. More
importantly, it helps improve re-usability.
• Each package in Java has its unique name and organizes its classes and
interfaces into a separate namespace, or name group.

Advantage of Java Package:


• Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
• Java package provides access protection.
• Java package removes naming collision.
• The classes present in the packages of other programs can be reused.
• Package provides the good ways of hide the classes.
• In package, classes can be unique i.e. two classes in two different packages
can have the same name.

There are two types of packages in Java:


1. Java API packages/Built-in packages.
2. User Defined packages.

Java API Packages/Built-in Packages:


• Java API provides a number of classes grouped into different packages
according to their functionality.
• The already defined package like java.io.*, java.lang.* etc. are known as
built-in packages.
• Below diagram shows Java API packages:

Fig. Java API Packages

• There are six main packages are present in Java programming language.
• Following table gives the information about the Java system packages
and their classes
Package Contents of the package
Name

java.lang Language support classes. They include classes for


primitive types, string, math functions, thread and
exceptions.

java.util Language utility classes such as vectors, hash tables,


random numbers, data, etc.

java.io Input/output support classes. They provide facilities


for the input and output of data.

java.applet Classes for creating and implementing applets.

java.net Classes for networking. They include classes for


communicating with local computers as well as with
internet
servers.

java.awt Set of classes for implementing graphical user


interface. They include classes for windows, buttons,
lists, menus and so on.

User defined Packages:


• Creating a package in java is quite easy.
• A package is always defined in a separate folder having the same name as a
package name.
• A package is a collection of related classes. It helps Organize your classes
into a folder structure and make it easy to locate and use them. More
importantly, it helps improve re-usability.
• Each package in Java has its unique name and organizes its classes and
interfaces into a separate namespace, or name group.
• The package must contain one or more classes or interfaces. This implies
that a package cannot be empty.
• The classes or interfaces that are in the package must have their source files
in the same directory structure as the name of the package.
• A package is always defined in a separate folder having the same name as a
package name.
• Define all 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 (So that its error
free)

Creation of packages includes following steps:


1. Declare the package at the beginning of the java source code file using
below syntax.
Syntax:
package package_name;
Above statement should be used in the beginning of the program to include that
program in that particular package.

2. Define a class which is to be put in the package and declare it public.


Example:
package first_pkg;

public class Hello


{
public void display()
{
System.out.println(“I am from Hello class:”);
}
}

In above example first_pkg is the package name and class Hello is added into it.

3. Create the subdirectory which has given the same name of package and
stored it into main directory where the source code is present.
4. Compile the source file, after that .class file stored into the subdirectory
which is created in step 3.

How to access package from another package/import statement:


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.* Statement then all the classes and interfaces of this
package will be accessible.
• import is a predefined keyword.
Syntax:
import Package_Name.*;

Example:
//Save by Abc.java
package first_pkg;
public class Abc
{
public void display()
{
System.out.println(“I am from Abc class:”);
}
}
//Save by Xyz.java
package
second_pkg;
import first_pkg.*;

class Xyz
{
public static void main(String args[])
{
Abc a1=new Abc(); a1.display();
}
}

Output:
I am from Abc class

2) import packagename.classname;
• If you use package.classname statement then only declared class of that
package will be accessible.
• import is a predefined keyword.
Syntax:
import Package_Name.classname;

Example:
//Save by Abc.java
package first_pkg;
public class Abc
{
public void display()
{
System.out.println(“I am from Abc class:”);
}
}//Save by Xyz.java
package
second_pkg;
import
first_pkg.Abc;

class Xyz
{
public static void main(String args[])
{
Abc a1=new Abc(); a1.display();
}
}

Output:
I am from Abc class

3) Using fully qualified name;


• If you use fully qualified name then only declared class of this package will
be accessible.
• No need to use the import keyword.
• 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:

//Save by Abc.java
package first_pkg;
public class Abc
{
public void display()
{
System.out.println(“I am from Abc class:”);
}
}
//Save by Xyz.java
package
second_pkg;
class Xyz
{
public static void main(String args[])
{
first_pkg.Abc a1=new first_pkg.Abc (); //using fully qualified name
a1.display();
}
}

Output:

I am from Abc class

Java Static Import


• The static import feature of Java is used to access any static member of a
class directly.
• There is no need to use the class name while accessing the static members.
• The static import statement can be used to import static members from
classes and use them without using class name.
• The difference between import and static import: - The import allows the
java programmer to access classes of a package without using package
name whereas the static import feature allows accessing the static members
of a class without using the class name.
• The import provides accessibility to classes and interface whereas static
import provides accessibility to static members of the class.
Syntax:
import static Package_Name.*;
or
import static Package_Name.classname;
Example:
import static java.lang. *;

class StaticImportDemo
{
public static void main(String args[])
{

System.out.println("Hello"); //Now no need of


System.out out.println("Java");
}
}
Output:
Hello Java

Advantage:
• Less coding is required if you have accessed any static member of a class.
Disadvantage:
• If you overuse the static import feature, it makes the program unreadable
and unmaintainable.

Package:
========
- Creating a package in java is quite easy.
- A package is always defined in a separate folder having the same name as a
package name.
- A package is a collection of related classes. It helps Organize your classes
into a folder structure and make it easy to locate and use them. More
importantly, it helps improve re-usability.
- Each package in Java has its unique name and organizes its classes and
interfaces into a separate namespace, or name group.
- The package must contain one or more classes or interfaces. This implies
that a package cannot be empty.
- The classes or interfaces that are in the package must have their source files
in the same directory structure as the name of the package.
- A package is always defined in a separate folder having the same name as a
package name.
- Define all 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 (So that its error
free)

Steps for creation of package:

1) Write below line as first line of java source file package packageName;
2) Write java class which you want to add inside the package and make it as
public
3) Create directory whose name same as package name and stored java file
inside it and compile it.
4) Access created package in another program using below different ways
import packageName.*;
OR
import packageName.className;

Example:

//Declare package msbte and make the class public


package msbte;
public class Sample
{
public void display()
{
System.out.println("display method of Sample class");
}
}
//Accessing msbte package
import msbte.*;
class AccessSamplePKG
{
public static void main(String args[])
{
Sample s1=new Sample();
s1.display();
}
}
OUTPUT:
=========================
display method of Sample class
=========================
Write a program to create package Math_s having two classes as addition
and subtraction. Use suitable methods in each class to perform basic
operations. *
=====================
//Creating Math_s package
package Math_s;
public class Addition
{
public void add(int x,int y)
{
System.out.println("Addition="+(x+y));
}
}
public class Subtraction
{
public void sub(int x,int y)
{
System.out.println("Subtraction="+(x-y));
}
}
//Accessing Math_s package
import Math_s.*;
class AccessMathPKG
{
public static void main(String args[])
{
Addition a1=new Addition();
Subtraction s1=new Subtraction();
a1.add(100,50);
s1.sub(500,300);
}
}

You might also like