0% found this document useful (0 votes)
26 views17 pages

Unit 3

Uploaded by

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

Unit 3

Uploaded by

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

Java Programming Notes

Chapter-3
1. Interface
As we know that java does not support multiple inheritance. That is classes in java cannot have more than
one superclass.eg. the definition given below is not allowed in java

Class A extends B extends C //not allowed in java

……

Java provides an alternative way to implement the concept of multiple inheritance through interfaces.
Although a java class cannot be subclass of more than one superclass, it can implement more than one
interface.

2. Defining an Interface
An interface is defined much like a class. This is the general form of an interface:

Syntax:
access interface name
{
static final type varname1 = value;
return-type method-name(parameter-list);
}

Here access is access specifier (public,private etc.)of interface. When no access specifier is included, then
default access specifier is considered. All methods and variables are implicitly public if the interface,
itself, is declared as public name is the name of the interface, and can be any valid identifier.

Notice that the methods which are declared have no bodies. They end with a semicolon after the
parameter list. They are, essentially, abstract methods; there can be no default implementation of any
method specified within an interface. Each class that includes an interface must implement all of the
methods.

Variables can be declared inside of interface declarations. They are implicitly finaland static, meaning
they cannot be changed by the implementing class. They must also be initialized with a constant value..

Example:

interface Area
{
Final static float pi=3.14f
void compute();
}

1
Prepared By:Vaishali C.Sanap
Java Programming Notes

3. Difference between class and interface


Following table shows the difference between class and interface.

Class Interface
1 It can contain abstract methods along with It can contain only method declarations and not
Method definitions. method definitions
2 Classes are extended by another class Interfaces are implemented by classes
3 Methods of objects can be called using the Methods of interfaces should be defined in the
object of the class class which implements the interface
4 The variables of the class can be final/not final The variables of the interfaces are by default
final
5 Object of class can be created Object of interface cannot be created
6 A class can extend only one class. An class can implement more than one interface.
Eg. Eg.
Class A extends B class A implements C,D
7 Multiple inheritance is not possible with classes Interface was introduced for the concept of
multiple inheritance
8 class Example interface Example
{ {
int x; Final int x =5;
void method1() void method1();
{ void method2();
body }
}
void method2()
{
body
}
}

4. Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To implement an
interface, include the implements clause in a class definition, and then create the methods defined by the
interface. The general form of a class that includes the implements clause looks like this:

Syntax:
access class class_name implements interface_name
{
//class body
}

Example:

2
Prepared By:Vaishali C.Sanap
Java Programming Notes

interface Area
{
final static float PI=3.14f;
void compute();
}

class Circle implements Area


{
int radius;
Circle(int r)
{
radius=r;
}
public void compute()
{
System.out.println("Area is: " + PI*radius*radius);
}
public static void main(String args[])
{
Circle c=new Circle(5);
c.compute();
}
}

Notice that compute( ) is declared using the public access specifier.

Output:
Area is :78.5

5. Accessing Interface variables and methods:


An interface may contain variables and constants. Variables can be declared inside of interface
declarations. They are implicitly final and static, meaning they cannot be changed by the implementing
class. They must also be initialized with a constant value.In some cases it may make sense to define
constants in an interface. Especially if those constants are to be used by the classes implementing the
interface.All variables in an interface are public, even if you leave out the public keyword in the variable
declaration.

An interface can contain one or more method declarations. As mentioned earlier, the interface cannot
specify any implementation for these methods. It is up to the implementing classes to specify an
implementation.All methods in an interface are public, even if you leave out the public keyword in the
method declaration.

Example:

interface Area
{
final static float PI=3.14f;

3
Prepared By:Vaishali C.Sanap
Java Programming Notes

int radius =5;


void compute();
}

class Circle implements Area


{
public void compute()
{
System.out.println("Area is: " + PI*Area.radius*Area.radius);
}
public static void main(String args[])
{
Circle c=new Circle();
c.compute();
}
}

Output:
Area is :78.5

6. Extending Interfaces
One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting
classes. When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain. Following is an example:

interface A
{
void meth1();
}
interface B extends A
{
void meth2();
}
class Myclass implements B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public static void main(String arg[])
{
Myclass ob = new Myclass();
ob.meth1();

4
Prepared By:Vaishali C.Sanap
Java Programming Notes

ob.meth2();
}
}

7. Interface References:
An interface is treated as abstracts, so we cannot instantiate interfaces or we cannot create an object of
interface. When you define a new interface, using following statement

interface interface_name;

You are defining a new reference data type. You can use interface names anywhere.

Let classA is implementing the interface. When you define a reference variable whose type is an
interface, any object you assign to it must be an instance of a classA that implements the interface.

interface interfacename;
classA c=new ClassA()
interfacename=c

Example1:

interface Square
{
int getArea() ;
}
class Rectangle implements Square
{
int width,height;
Rectangle (int w,int h)
{
width=w;
height=h;
}
public int getArea()
{
return width * height;
}

public static void main(String args[])


{

Rectangle r=new Rectangle (10,20);


// Square s= new Square (); Create error :Square is abstract cannot instantiated

Square s = r;

5
Prepared By:Vaishali C.Sanap
Java Programming Notes

System.out.println(“Area is:” +s.getArea());

}
}
Output:

Area is=200

Example2:

interface Square
{
public void larger(Square other); //creating instance reference
}
class Rectangle implements Square
{
int width,height;
Rectangle (int w,int h)
{
width=w;
height=h;
}
int getArea()
{
return width * height;
}
public void larger(Square other)
{
Rectangle otherone = (Rectangle)other;
if (this.getArea() < otherone.getArea())
System.out.println("object1 is smaller than object2");
else if (this.getArea() > otherone.getArea())
System.out.println("object1 is greater than object2");
else
System.out.println( "object1 is equal to object2");
}
public static void main(String args[])
{
Rectangle c1=new Rectangle (10,20);
Rectangle c2=new Rectangle (20,20);
c1.larger(c2);

}
}
Output:

object1 is smaller than object2

6
Prepared By:Vaishali C.Sanap
Java Programming Notes

8. Nested Interface
An interface which is declared within another interface or class is known as nested interface. The nested
interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface
must be referred by the outer interface or class. It can't be accessed directly.

Syntax:
interface interface_name
{ ...
interface nested_interface_name
{
...
}
}

Example:
interface Showable
{
void show();
interface Message
{
void msg();
}
}

class Test implements Showable


{
public void show()
{
System.out.println("Outer interface");
}
public void msg()
{
System.out.println("Nested interface");
}

public static void main(String args[])


{
Test t1=new Test();
t1.show();
t1.msg();
}
}

Output:
Outer Interface
Nested Interface

7
Prepared By:Vaishali C.Sanap
Java Programming Notes

9. Multiple Inheritance Through Interfaces


Deriving a class from more than one class gives you the concept of multiple inheritance. Interface is one
of alternative way to achieve multiple inheritance. Following example shows how we will achieve this
concept.

Example1:

Interface Exam Class Sports

marks1,marks2 score
display() accept()

Class Result

total

interface Exam
{
static final int marks1=70;
static final int marks2=80;
abstract void display();
}
class Sports
{
int score;
void accept(int s)
{
score=s
}
}
class Result extends Sports implements Exam
{
public void display()
{
System.out.println(“Total=”+(marks1+marks2+score));
}

public static void main(String args[])


{
Result r=new Result();
r.accept(60);
r.display();
}
}

8
Prepared By:Vaishali C.Sanap
Java Programming Notes

Example2:

Interface Exam Interface Sports

marks1,marks2 score
display()

Class Result

total

interface Exam
{
static final int marks1=70;
static final int marks2=80;
abstract void display();

}
interface Sports
{
static final int score=60;

}
class Result extends Sports implements Exam
{
public void display()
{
System.out.println(“Total=”+(marks1+marks2+score));
}

public static void main(String args[])


{
Result r=new Result();
r.display();

}
}

9
Prepared By:Vaishali C.Sanap
Java Programming Notes

10.Packages:
Packages are collection of classes and interface or packages act as container for classes. By organizing
our classes into packages we achieve following benefits:

1. Easy to reuse the classes and interfaces which are defined in packages.
2. Two classes in different packages can have same name e.g. student class in package1 and student
class in package2.
3. It provides a way to hide a class thus prevent other programs or packages to access this class.
4. provide a way for separating design with coding.

Java API provides a large number of classes which are grouped into different packages according to
functionality. Following diagram shows the built in packages of java.

Java

lang util io awt net applet

Sr no Package name contents


1 java.lang Language support classes. They are used by java compiler itself and
thus automatically imported. They include classes for primitive
types, strings, math, tread and exceptions.
2 java.io Input/output support classes. They provide support for input and
output.
3 java.util Language utility classes such as Vector, Date ,hash tables, random
numbers etc.
4 java.awt Set of classes for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.
5 java.applet Classes for creating and implementing applets.
6 java.net Classes for networking. They include classes for communication with
local computers as well as with internet servers.

10
Prepared By:Vaishali C.Sanap
Java Programming Notes

Naming of Packages:

 When one want to use a package he/she can use full qualified name as given below:

import java.util.Vector

 The java package has subpackages like awt, applet, io, lang, net, and util.
 If you want to work on a specific class (Vector) of a package then mention it as given above.
 If you are working with more than one class(Vector and Date) of a package then use

import java.util.*;

11. Creating Packages (Defining a Package)


To create a package is quite easy: simply include a package command as the first statement in a Java
source file.This is the general form of the package statement:

package pkg_name;

Here, pkg_name is the name of the package. For example, the following statement creates a
package called MyPackage.

MyPackage1/ClassA.java

package MyPackage;
public class ClassA
{
int x;
public void accept(int x1)
{
x=x1;
}
public void display()
{
System.out.println(“X=”+x);
}
}

Note that the access specifier of class and methods is public to make it visible in all programs. Save this
file as ClassA.java in MyPackage folder which you have created in bin directory of JDK.
Compile this file as given below

C:\jdk\bin>javac MyPackage\ClassA.java

11
Prepared By:Vaishali C.Sanap
Java Programming Notes

12. Import a package (Accessing Packages)


After defining a package, it’s time to use the package in another program. To do so there is need to use
import statement to include the package in your program. To import a package the following sysncat can
be use

import pkg1[.pkg2].(classname|*);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the
outer package separated by a dot (.). There is no practical limit on the depth of a package hierarchy,
except that imposed by the file system. Finally, you specify either an explicit classname or a star (*),
which indicates that the Java compiler should import the specific class or the entire package as given
below

import java.util.Vector; //this will import only Vector class


Or
import java.util.* //this will import all the classes of util package

Following code shows how to import the user defined package(Previously created)

Sample.java
import MyPackage.*;
class Sample
{
public static void main(String args[])
{
ClassA a=new ClassA();
a.accept(5);
a.display();
}
}

Save this file as Sample.java in bin directory of JDK.


Compile and run file using following commands on command prompt

C:\jdk\bin>javac Sample.java
C:\jdk\bin>java Sample

And you will get the desired uoyput i.e. X=5.

13. Package with Multiple Classes

As package is collection of classes and interface. A java package file can have more than one class
definitions. In such cases only one of the classes may be declared as public and that class name with .java

12
Prepared By:Vaishali C.Sanap
Java Programming Notes

extension is the source file name. In one notepad file only one of the class can be declared as public so to
create multiple public classes need to write code in separate files. Following example shows how to create
two public classes in sample package.

Step1:Open notepad and write code

MyPackage1/ClassA.java
package MyPackage;
public class ClassA
{
int x;
public void accept(int x1)
{
x=x1;
}
public void display()
{
System.out.println(“X=”+x);
}
}

Step2: Save this file as ClassA.java in MyPackage folder which you have created in bin directory of JDK.
Compile this file as given below

C:\jdk\bin>javac MyPackage\ClassA.java

Step3: Open notepad and write code

MyPackage/ClassB.java
package MyPackage;
public class ClassB
{
int y;
public void accept(int y1)
{
y=y1;
}
public void display()
{
System.out.println(“Y=”+y);
}
}
Step4:
Save this file as ClassB.java in MyPackage folder which you have created in bin directory of JDK.
Compile this file as given below

C:\jdk\bin>javac MyPackage\ClassB.java

13
Prepared By:Vaishali C.Sanap
Java Programming Notes

Step5: Open notepad and write code

Sample.java
import MyPackage.*;
class Sample
{
public static void main(String args[])
{
ClassA a=new ClassA();
ClassB b=new ClassB();
a.accept(5);
a.display();
b.accept(10);
b.display();

}
}

Step6:
Save this file as Sample.java in bin directory of JDK.
Compile and run file using following commands on command prompt

C:\jdk\bin>javac Sample.java
C:\jdk\bin>java Sample

And you will get the desired uoyput i.e.


X=5
Y=10

14. Two Packages with Same Class Name


One of the benefits of package is that we can use same class name in two or more different
packages .example is shown below.

Step1: Open notepad and write code


MyPackage1/Student.java
package MyPackage1;
public class Student
{
int rollno;
public void accept(int r)
{
rollno=r;
}
public void display()
{
System.out.println(“Roll no=”+rollno);
}
}

14
Prepared By:Vaishali C.Sanap
Java Programming Notes

Step2:
Save this file as Student.java in MyPackage1 folder which you have created in bin directory of JDK.
Compile this file as given below

C:\jdk\bin>javac MyPackage1\Student.java

Step3: Open notepad and write code

MyPackage2/Student.java
package MyPackage2;
public class Student
{
String name;
public void accept(String n)
{
Name=n;
}
public void display()
{
System.out.println(“Name=”+name);
}
}
Step4:
Save this file as Student.java in MyPackage2 folder which you have created in bin directory of JDK.
Compile this file as given below

C:\jdk\bin>javac MyPackage2\Student.java

Step5: Open notepad and write code

Sample.java

import MyPackage1.*;
import MyPackage2.*;

class Sample
{
public static void main(String args[])
{
MyPackage1.Student s1=new MyPackage1.Student ();
MyPackage2.Student s2=new MyPackage2.Student ();
S1.accept(1001);
S1.display()
S2.accept(“abc”)
S2.display();
}
}

Step6:
Save this file as Sample.java in bin directory of JDK.

15
Prepared By:Vaishali C.Sanap
Java Programming Notes

Compile and run file using following commands on command prompt

C:\jdk\bin>javac Sample.java
C:\jdk\bin>java Sample

And you will get the desired uoyput i.e.


Rollno=1001
Name= abc

15. Package with Class and interface


As a package is collection of classes and interfaces. We can add classes and interfaces in a package.
Following example illustrate this concept:

Example 1:
MyPackage/Sample.java
package MyPackage;

interface Demo
{
void display();
}
public class Sample implements Demo
{
public void show()
{
System.out.println("Printing from class");
}
public void display()
{
System.out.println("Printing from interface");
}

Example.java
import MyPackage.*;
class Example
{

public static void main(String args[])


{
Sample s=new Sample();
s.show();
s.display();
}
}

Output:

16
Prepared By:Vaishali C.Sanap
Java Programming Notes

Printing from class


Printing from interface

Example2:

MyPackage /Sample.java

package MyPackage;
public class Sample
{
public void show()
{
System.out.println("Printing from class");
}

MyPackage /Demo.java

package MyPackage;
public interface Demo
{
public void display();

Example.java
import MyPackage.Sample;
import MyPackage.Demo;

class Example extends Sample implements Demo


{
public void display()
{
System.out.println("Printing from interface");
}
public static void main(String args[])
{
Example e=new Example();
e.show();
e.display();
}
}
Output:

Printing from class


Printing from interface

17
Prepared By:Vaishali C.Sanap

You might also like