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

JAVA UNIT-II (Part-1)

Uploaded by

Shivasainath .k
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)
19 views

JAVA UNIT-II (Part-1)

Uploaded by

Shivasainath .k
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/ 23

R 20 OOPS THROUGH JAVA

UNIT - II
PACKAGES

PACKAGES
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-
defined package. There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
2) Java package provides access protection.

[1] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

3) Java package removes naming collision.

Example:
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.printl
n("Welcome to
package");
6. }
7. }

CLASSPATH
run java package program:
Syntax : Package <Packagename> // at the start of the program.

To Compile: javac –d. Simple.java


To Run: java mypack.Simple
Note: The -d is a switch that tells the compiler where to put the class file i.e.
it represents destination. The . represents the current folder.

ACCESS PROTECTION IN JAVA PACKAGES

In java, the access modifiers define the accessibility of the class and its members.
For example, private members are accessible within the same class members only.

[2] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

Java has four access modifiers, and they are default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-
packages. The class acts as a container of data and methods. So, the access
modifier decides the accessibility of class members across the different packages.
In java, the accessibility of the members of a class or interface depends on its
access specifiers. The following table provides information about the visibility of
both data members and methods.

🔔 The public members can be accessed everywhere.


🔔 The private members can be accessed only inside the same class.

🔔 The protected members are accessible to every child class (same package or
other packages).
🔔 The default members are accessible within the same package but not outside the
package.

Let's look at the following example java code.

[3] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

Example:
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass{
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d);// private member can't be
accessed
}
}
public class AccessModifiersExample {

[4] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
obj.accessData();
}
}

IMPORTING PACKAGES

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.* then all the classes and interfaces of this
package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of
another package accessible to the current package.

Example:
1. //save by A.java
2. package pack;
3. public class A{
4. public void

[5] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

msg(){System.out.pri
ntln("Hello");} 5. }

1. //save by B.java
2. import pack.*;
3. class B{
4. public static void main(String args[]){
5. A obj = new A();
6. obj.msg();
7. } }

2) Using packagename.classname

If you import package.classname then only declared class of this package


will be accessible.
Example:
1. //save by A.java
2. package pack;
3. public class A{
4. public void
msg(){System.out.pri
ntln("Hello");} 5. }

1. //save by B.java
2. import pack.A;
3. class B{
4. public static void main(String args[]){
5. A obj = new A();

[6] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

6. obj.msg();
7. } }

3) Using fully qualified name

If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. 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:
1. //save by A.java
2. package pack;
3. public class A{
4. public void
msg(){System.out.pri
ntln("Hello");} 5. }

1. //save by B.java
2. class B{
3. public static void main(String args[]){
4. pack.A obj = new pack.A();//using fully qualified name
5. obj.msg();
6. } }

INTERFACES

[7] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

An interface in java is a blueprint of a class. It has static constants and abstract


methods.

The interface in Java is a mechanism to achieve abstraction. There can be


only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body. It cannot be instantiated just like
the abstract class.

There are mainly three reasons to use interface.


o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

An interface is declared by using the interface keyword. It provides total


abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default. A class
that implements an interface must implement all the methods declared in the
interface.

Syntax:
1. interface <interface_name>{
2. // declare constant fields
3. // declare methods that abstract

[8] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

4. // default. 5. }

Note: The Java compiler adds public and abstract keywords before the interface
method. Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.

The relationship between classes and interfaces


a class extends another class, an interface extends another interface, but a class
implements an interface.

Example:
1. interface printable{
2. void print(); 3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6. public static void main(String args[]){
7. A6 obj = new A6();
8. obj.print();

[9] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

9. }}

Example:
1. //Interface declaration: by first user

2. interface Drawable{
3. void draw(); 4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");
8. }
9. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//
16. d.draw(); 17. }}

IMPLEMENTING AN INTERFACE IN JAVA


In java, an interface is implemented by a class. The class that implements an
interface must provide code for all the methods defined in the interface, otherwise,
it must be defined as an abstract class.
The class uses a keyword implements to implement an interface. A class can

[10] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

implement any number of interfaces. When a class wants to implement more than
one interface, we use the implements keyword is followed by a comma-separated
list of the interfaces implemented by the class.
The following is the syntax for defineing a class that implements an interface.
Syntax

class className implements InterfaceName{


...
body-of-the-class
...
}

Let's look at an example code to define a class that implements an interface.


Example
Example:
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6. public static void main(String args[]){
7. A6 obj = new A6();
8. obj.print();
9. }
10. }
In the above code defines an interface printable that contains a abstract method
print(). The class A6 implements the interface. As it implementing the printable

[11] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

interface it must provide the body of the method those defined in the printable
interface.

MULTIPLE INHERITANCE IN JAVA BY INTERFACE


(APPLYING INTERFACES)
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.

Example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. A7 obj = new A7();
12. obj.print();
13. obj.show();

[12] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

14. }}

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.

Example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7. class TestInterface3 implements Printable, Showable{
8. public void print(){System.out.println("Hello");}
9. public static void main(String args[]){
10. TestInterface3 obj = new TestInterface3();
11. obj.print();
12. }}

Interface inheritance
A class implements an interface, but one interface extends another interface.
Example:
1. interface Printable{
2. void print();
3. }

[13] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

4. interface Showable extends Printab{


5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. TestInterface4 obj = new TestInterface4();
12. obj.print();
13. obj.show(); 14. } }

Default Method in Interface


we can have method body in interface. But we need to make it default method.
Let's see an example:
1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }

5. class Rectangle implements Drawable{


6. public void draw(){System.out.println("drawing rectangle");} 7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}

[14] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

Static Method in Interface


we can have static method in interface. Let's see an example:
1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;
4. }
}
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");} 7. }
8. class TestInterfaceStatic{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. System.out.println(Drawable.cube(3));
13. }}

NESTED INTERFACE IN JAVA

An interface i.e. 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

[15] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

accessed directly.

Points to remember:
o Nested interface must be public if it is declared inside the interface but it can
have any access
modifier if declared within the class.
o Nested interfaces are declared static implicitely.

Syntax of nested interface which is declared within the interface:


1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. } }

Syntax of nested interface which is declared within the class :


1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. } }

Example of nested interface which is declared within the interface :


1. interface Showable{
2. void show();
3. interface Message{
4. void msg();

[16] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

5. } }
6. class TestNestedInterface1 implements Showable.Message{
7. public void msg(){System.out.println("Hello nested interface");}
8. public static void main(String args[]){
9. Showable.Message obj=new TestNestedInterface1();//upcasting here
10.obj.msg();
11. } }

As you can see in the above example, we are accessing the Message interface by
its outer interface
Showable because it cannot be accessed directly. In collection frameword, sun
microsystem has provided a nested interface Entry. Entry is the subinterface of
Map i.e. accessed by Map.Entry.
Internal code generated by the java compiler for nested interface Message

The java compiler internally creates public and static interface as displayed below:
1. public static interface Showable$Message
2. {
3. public abstract void msg();
4. }

Example of nested interface which is declared within the class :


1. class A{
2. interface Message{
3. void msg();

[17] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

4. } }
5. class TestNestedInterface2 implements A.Message{
6. public void msg(){System.out.println("Hello nested interface");}
7. public static void main(String args[]){
8. A.Message obj=new TestNestedInterface2();//upcasting here
9. obj.msg();
10. } }

If we define a class inside the interface, java compiler creates a static nested class.
Let's see how can
we define a class within the interface:
1. interface M{
2. class A{}
3. }

INTERFACE VARIABLES
A Java interface can contain both variables and constants. However, often it does
not makes sense to place variables in an interface. In some cases it can make sense
to define constants in an interface.
Especially if those constants are to be used by the classes implementing the
interface, e.g. in calculations, or as parameters to some of the methods in the
interface. However, my advice to you is to avoid placing variables in Java
interfaces if you can.

All variables in an interface are public, even if you leave out the public keyword in
the variable declaration

[18] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

EXTENDING INTERFACES
An interface can extend another interface in the same way that a class can extend
another class.
The extends keyword is used to extend an interface, and the child interface inherits
the methods of
the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);

public void setVisitingTeam(String name);


}

// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();

[19] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

public void endOfPeriod(int period);


public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a
class that implements Hockey needs to implement all six methods. Similarly, a
class that implements Football needs to define the three methods from Football
and the two methods from sports.
Extending Multiple Interfaces
A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one
parent interface.
The extends keyword is used once, and the parent interfaces are declared in a
comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be
declared as −
Example
public interface Hockey extends Sports, Event

Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be
instantiated.
But there are many differences between abstract class and interface that are given
below.

[20] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

Abstract Interface
class

1) Abstract class can have Interface can have only abstract


abstract and non- abstract methods. Since Java 8, it can have
methods. default and static methods also.

2) Abstract class doesn't Interface supports multiple inheritance.


support multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables.
variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

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


declare abstract class. interface.

6) An abstract class can extend An interface can extend another Java


another Java class and implement interface only.
multiple Java interfaces.

7) An abstract class can be extended An interface can be implemented


using keyword "extends". using keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface


achieves fully
abstraction (100%).
[21] Syeda Sumaiya
Afreen
R 20 OOPS THROUGH JAVA

Let's see a simple example where we are using interface and abstract class both.
1. //Creating interface that has 4 methods
2. interface A{
3. void a();//bydefault, public and abstract
4. void b();
5. void c();
6. void d();
7. }
8. //Creating abstract class that provides the implementation of one method of A
interface
9. abstract class B implements A{
10. public void c(){System.out.println("I am C");}
11. }
12. //Creating subclass of abstract class, now we need to provide the
implementation of rest of the methods
13. class M extends B{
14. public void a(){System.out.println("I am a");}
15. public void b(){System.out.println("I am b");}
16. public void d(){System.out.println("I am d");}
17. }
18. //Creating a test class that calls the methods of A interface
19. class Test5{
20. public static void main(String args[]){
21. A a=new M();
22. a.a();
23. a.b();
24. a.c();

[22] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

25. a.d();
26. }
27. }

[23] Syeda Sumaiya


Afreen

You might also like