Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit-2 Java

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 12

packages

Definition: It is a collection of related classes, each class defines number of methods,

Java packages can be stored in compressed files called JAR files, allowing classes to be
downloaded faster as groups rather than individually. In general, a package can contain the
following kinds of types: classes, interfaces, enumerations, and annotation types. Java packages
are classified in two types.

1.Java API: These are defined by the system


Ex: Java.lang.util. java.io, java.awt, java.applet.
Example: Import java.util.Scanner;
 java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.

2. User defined packages: these are defined by the users.

Defining a package: to define a package place “package” command as the first statement in the
java sourcefile.so that the class declared within that ,file will belongs to the specified package.
Syntax: Package pack-name
Public class number
{
Public void add (int a, int b)
{
System.out.println (“sum=”+ (a+b));
}
}
Example of package:
Package mypack
Public class number
{
Public static void main(String args[])
{
System.out.println(“ADDIION of a,b=:” +(a+b));
}
}
Import mypack.number;
Class demokits
{
Public static void main(String args[])
{
Number nn=new number();
nn.add(10,20);
}
}
Important principles of packages
Define a package must be in public accesses specifies
Java users file system directories to store packages
User import keyword that links to the package. Advantages of packages:
The classes defined in the packages of other programs can be easily re used.
Two classes from two different packages can have the same name.
Packages can provide separate two phases i.e. design, coding.
Using packages we can hide the classes.
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.
Advantages of using a package in Java
These are the reasons why you should use packages in Java:
Reusability: While developing a project in java, we often feel that there are few things that we
are writing again and again in our code. Using packages, you can create such things in form of
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
Creating and accessing packages.
Step 1 : create the folder with name
Ex:sahitya_mypack

Step 2 : write the “sahitya_animal.java” program and place in “sahitya_mypack” folder.then


save ctrl+s
Step 3 : write the “sahitya_dog.java” program and place in “sahitya_mypack” folder.then save
ctrl+s

Step 4 : write the driver class of “sahitya_cse.java” program


Then import the both classes which are placed in sahitya_mypack like

D :\> set CLASSPATH=.;D:\;

D:\>cd sahitya_mypack>javac sahitya_cse.java;

D:\>sahitya_mypack>java sahitya_cse;

step 5: it will shows result from both classes of pack

example 2 of packages:
package sahitya_mypack;
public class sahitya_animal
{
public void eat()
{
System.out.println("all animals are eat");
}
}
package sahitya_mypack;
public class sahitya_dog
{
public void eat()
{
System.out.println("all dogs are also eat");
}
}
import sahitya_mypack.sahitya_animal;
import sahitya_mypack.sahitya_dog;
public class sahitya_cse //driver class
{
public static void main(String[] args)
{
sahitya_animal sa=new sahitya_animal();
sa.eat();
sahitya_dog sda=new sahitya_dog();
sda.eat();
}
}
//Output: all animals are eat
//all dogs are also eat

Sub-packages:
A package inside another package is known as sub package. For example If I create a
package inside letmecalculate package then that will be called sub package.
Example program:
package pack1
public class cseb
{
Public void show()
{
Syatem.out.println(“main package”);
}
}
Package pack1.pack2;
Public class csea
{
Public void disply()
{
System.out.println(“sub package”);
}
}
Import pack1.cseb;
Import pack1.pack2.csea;
Class demokits
{
Public static void main(String args[])
{
cseb cs=new cseb();
cs.show();
csea cc=new csea();
cc.display();
}
}
Interface
Definition: 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
inheritances in Java. Java Interface also represents IS-A relationship. It cannot be instantiated
just like abstract class.
Java class can not be a subclass of more than one super class it can be implemented with
interface concept.
What is the reason to use interface in java
There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritances.
It can be used to achieve loose coupling.
General format of an interface:
Interface <interface name>
{
Declarative variables;
Declarative methods;
}
Interface is the keyword interface name is any valued java variable just like a class name;
The variable declaration as follows
Static final type variable name=value;
All variables are declared as constants.
Example of interface:
Interface item
{
Static final int code=1001;
Static final stringname=”fan”;
Void display();
}

The relationship between classes and interfaces


Important points about interface or summary of article:
We can’t create instance (interface can’t be instantiated) of interface but we can make
reference of it that refers to the Object of its implementing class.
A class can implement more than one interface.
An interface can extends another interface or interfaces (more than one interface) .
A class that implements interface must implements all the methods in interface.
All the methods are public and abstract. And all the fields are public, static, and final.
It is used to achieve multiple inheritances.
It is used to achieve loose coupling.
Extending interface: like a classes the interface can also be extended
(i.e. an interface can be sub interfaced from other interfaces, the new sub interface inherits all
the members of super interface)
Ex: interface name2 extends name1
{
------
Body of name2;
------
}
Ex2:
Inter face itemconstants
{
Int code =1001;
String name=”fan”;
}
Interface item extends itemconstants
{
Void display ();
}
Implementing of interface:
Interfaces are used to super classes whose properties are inherited by classes; it is necessary to
create a class.
Syntax:
Class classname implements interfacename
{
Body of the program;
}
Here the class name implements by when a class implemented more than one interfaces are
separated by coma..
Example:
Class classname extends superclass
Implements interface1, interface2
{
Body of the classname;
}
Implement the Multiple inheritances in Java by using interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.
Multiple inheritances is not supported in case of class because of ambiguity. But it is
supported in case of interface because there is no ambiguity as implementation is
provided by the implementation class.
For example:
Implement the multiple inheritances using interface sample program.
import java.io.*;
interface father
{
float ht=6.2f;
void height();
}
interface mother
{
float ht=5.8f;
void height();
}
class child implements father,mother
{
public void height()
{
float ht=(father.ht+mother.ht)/2 ;
System.out.println("height is =:" + ht);
}
}
public class rosy_prog //driver class
{
public static void main(String[] args)
{
child ch=new child();
ch.height();
}
}

Output: height is =:6.0

Example2:
import java.io.*;
import java.Lang.Math;
import java.inpurDatastream;
Interface area
{
Final static float pi=3.142;
Float compute (float x, float y);
}
Class rectangle implements area
{
Public float compute (float x, float y)
{
Return x*y;
}
}
Class circle implements area
{
Public float compute (float x, float y)
{
Return x*y;
}
}
Class interest
{
Public static void main (String args [])
{
Area area =new Area();
Rectangle rec=new rectangle ();
Circle cir=new circle();
Area=rec;
System.out.println(“area of rectangle=” +area.compute(10,20));
Area=cir;
System.out.println(“area of circle=” +area.compute(10,20));
}
}

Stream: is an abstraction that either produces of consuming information i.e flow of data
Or
It is a logical connection between java program and the file which will used to send the data
through stream from java program to file, and data read from file through stream to java
program.
->It is linked to physical device by its java i/o system.

->An input stream can abstract many kinds of i/p from a disk file, keyboard, and network socket

->O/P stream refers to file, network connection, printer

->when a file is opened on object is created and stream is associated with the object
-Three stream objects are created by the java system.

1. System.in,
2. System.out,
3. System.err
->System. In: It is a standard i/p stream object. It enables a program to i/p byte from the
keyboard.

->System. Out: It is standard output stream object. It enables a program to output data to the
screen

->System.err: It is a standard error stream object it enables a program to output errpr message
on the screen.

I/o stream hierarchy

I/o streams

Byte system Character stream

Input stream Output stream reader Writer

Byte stream: Provides a convenient way for handling input and output of bytes of data
Character stream: Provides a convenient way for handling input/output of character data

Byte streams classes are used for processing the data in the form of bytes. This class defines two
important abstract classes called Input stream, output stream.

Byte stream

Input stream Output stream

Input stream: It is an abstract class used to stream input byte. It reads the data in the form of
bytes from the physical device using i/p stream. It contains the following methods.

1. Int available () : Return number of bytes of input

2. Void close() : Close the i/p stream

3. Int read () : Reads the next byte of data from the i/p stream. Int range of value 0 to 255.If no
bytes having the end of byte value is -1 then returned.

4. Int read (byte[]b): It attempt to read no. of bytes

5.Int read(byte[]b,int ff,int n) : It attempts to read no.og bytes into bytes rray

6.Long skip(long n): Skips over and discuss n bytes of data from the i/p.
Output Stream: It is an abstract class that defines java’s model of streaming byte output.the
system is sending the data in the form of bytes to the physical devices using output stream.It
having the following methods.

1. Void close(): Used to close stream

2. Void flush(): Clear’s the O/P buffer

3. Void write(int b): Write single bytes

4. Void write(byte buf[]): Write the specified array length

5. Void write(byte buf[],int off,int len): Written length of bytes from the specified bytes

Reading console input:

You might also like