Unit II
Unit II
NOTES
UNIT II - INHERITANCE, PACKAGES AND
INTERFACES
SL NO TOPIC
UNIT – I
1 OVERLOADING METHODS
2 OBJECTS AS PARAMETERS
3 RETURNING OBJECTS
4 STATIC, NESTED AND INNER CLASSES
5 INHERITANCE: BASICS
6 TYPES OF INHERITANCE
7 SUPER KEYWORD
8 METHOD OVERRIDING
9 DYNAMIC METHOD DISPATCH
10 ABSTRACT CLASSES
11 FINAL WITH INHERITANCE
12 PACKAGES AND INTERFACES: PACKAGES
13 PACKAGES AND MEMBER ACCESS
14 IMPORTING PACKAGES
15 INTERFACES
.–––.
1. OVERLOADING METHODS
Overloading Methods
When two or more methods within the same class that have the same name, but their
parameter declarations are different.
The methods are said to be overloaded, and the process is referred to as method
overloading. Method overloading is one of the ways that Java supports polymorphism.
Example:
// Demonstrate method overloading.
class OverloadDemo
{ void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.void test(int a)
{ System.out.println("a: " + a);
}
// Overload test for two integer parameters.void test(int a, int b)
{ System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double parameterdouble test(double a) { System.out.println("double a:
" + a); return a*a;
}
}
class Overload {
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
2. OBJECTS AS PARAMETERS
Method Overriding
When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the
superclass.
When an overridden method is called from within its subclass, it will always refer to
the version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
Example:
// Method overriding.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and jvoid show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
// display k – this overrides show() in Avoid show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Output:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used.
If you wish to access the superclass version of an overridden method, you can do so by using
super.
For example, in this version of B, the superclass version of show( ) is invoked within the
subclass’ version.
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
Output:
i and j: 1 2
k: 3
Here, super.show( ) calls the superclass version of show( ).
3. RETURNING OBJECTS
Returning Objects
In java, a method can return any type of data, including objects.
For example, in the following program, the incrByTen( ) method returns an object in which
the value of an (an integer variable) is ten greater than it is in the invoking object.
class ObjectReturnDemo
{ int a;
// Constructor
ObjectReturnDemo(int i) { a = i; }
// Class 2
// Main class
public class GFG {
ob2 = ob1.incrByTen();
Static variables
1. When a variable is declared as static, then a single copy of variable is created and
shared among all objectsat class level. Static variables are, essentially, global
variables. All instances of the class share variables
2. methods
3. nested classes
Static blocks
If you need to do computation in order to initialize your static variables, you can declare a
static block thatgets executed exactly once, when the class is first loaded.
Static methods
When a method is declared with static keyword, it is known as static method. When a
member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object. The most common example of a static method is main( )
method. Methods declared as static have several restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
class one
{
static int a=3;
static int b;
static void meth(int x)
{
System.out.println("the value x is" +x);
System.out.println("the value a is" +a);
System.out.println("the value b is" +b);
}
static
{
System.out.println("Inside static
Block"); b=a*4;
}
public static void main(String[] args)
{
meth(50);
}
}
class EnclosingClass {
...
class ANestedClass {
...
}
}
You use nested classes to reflect and to enforce the relationship between two classes.
You should define a class within another class when the nested class makes sense only in the
context of its enclosing class or when it relies on the enclosing class for its function.
For example, a text cursor might make sense only in the context of a text component.
It has unlimited access to its enclosing class's members, even if they are declared private. However,
this special privilege isn't really special at all.
It is fully consistent with the meaning of private and the other access specifiers. The access specifiers
restrict access to members for classes outside the top-level class.
The nested class is inside its enclosing class so that it has access to its enclosing class's members.
Like other members, a nested class can be declared static (or not).
class EnclosingClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
As with static methods and variables, which we call class methods and variables, a static nested class
is associated with its enclosing class.
And like class methods, a static nested class cannot refer directly to instance variables or methods
defined in its enclosing class — it can use them only through an object reference.
As with instance methods and variables, an inner class is associated with an instance of its
enclosing class and has direct access to that object's instance variables and methods.
Also, because an inner class is associated with an instance, it cannot define any static
members itself.
Both static nested classes and inner classes have member scope. Member scope means that
the type is defined directly in the body of the enclosing class — it is a member of the class.
To help further differentiate the terms nested class and inner class, it's useful to think about
them in the following way.
The term nested class reflects the syntactic relationship between two classes; that is,
syntactically, the code for one class appears within the code of another.
In contrast, the term inner class reflects the relationship between objects that are instances of
the two classes.
class EnclosingClass {
...
class InnerClass {
...
}
}
The interesting feature about the relationship between these two classes is not that InnerClass is
syntactically defined within EnclosingClass. Rather, it's that an instance of InnerClass can exist only
within an instance of EnclosingClass and that it has direct access to the instance variables and
methods of its enclosing instance. The next figure illustrates this idea.
Additionally, there are two special kinds of inner classes: local classes and anonymous classes (also
called anonymous inner classes). Both of these will be discussed in the next section.
You may encounter all of these nested classes in the Java platform API and be required to use them.
INNER CLASSES
Inner class means one class which is a member of another class.
Example:
class Outer {
// Simple nested inner class class Inner {
Example:
class Outer {
void outerMethod() { System.out.println("inside outerMethod");
// Inner class is local to outerMethod() class Inner {
void innerMethod() { System.out.println("inside innerMethod");
}
}
Inner y = new Inner(); y.innerMethod();
}
}
class MethodDemo {
public static void main(String[] args) { Outer x = new Outer(); x.outerMethod();
}
}
Output:
Inside outerMethod Inside innerMethod
Example:
class Outer {
private static void outerMethod() { System.out.println("inside outerMethod");
}
// A static inner class static class Inner {
public static void main(String[] args) { System.out.println("inside inner class Method");
outerMethod();
}
}
}
Output:
inside inner class Method inside outerMethod
In the above code, we have two class Demo and Flavor1Demo. Here demo act as super class and
anonymous class acts as a subclass, both classes have a method show().
Example:
class Flavor2Demo {
// An anonymous class that implements Hello interface static Hello h = new Hello()
{ public void show() {
System.out.println("i am in anonymous class");
}
};
public static void main(String[] args) { h.show();
}
}
interface Hello { void show(); }
Output:
i am in anonymous class
In above code we create an object of anonymous inner class but this anonymous inner class is an
implementer of the interface Hello. Any anonymous inner class can implement only one interface at
one time. It can either extend a class or implement interface at a time.
5. INHERITANCE : BASICS
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behaviors of one class to another, i.e., acquiring the properties and behavior of child class
from the parent class.
When one object acquires all the properties and behaviours of another object, it is known as
inheritance.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Syntax:
class subClass extends superClass
{
//methods and fields
}
6. TYPES OF INHERITANCE
6.1 Introduction to Types of Inheritance
a) SINGLE INHERITANCE
In Single Inheritance one class extends another class (one class only).
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference ClassB b = new ClassB();
//call dispA() method of ClassA b.dispA();
//call dispB() method of ClassB b.dispB();
}
}
Output :
disp() method of ClassA
disp() method of ClassB
b) MULTILEVEL INHERITANCE
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived
classbecomes the base class for the new class.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
c) HIERARCHICAL INHERITANCE
In Hierarchical Inheritance, one class is inherited by many sub classes.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
Output :
disp() method of ClassB
disp() method of
ClassA disp() method
of ClassC disp() method
of ClassA disp()
method of ClassD
disp() method of ClassA
d) HYBRID INHERITANCE
Hybrid Inheritance is the combination of both Single and Multiple Inheritance.
Again Hybrid inheritance is also not directly supported in Java only through interface we can
achieve this.
As you can ClassA will be acting as the Parent class for ClassB & ClassC and ClassB & ClassC
will be acting as Parent for ClassD.
e) MULTIPLE INHERITANCE
Multiple Inheritance is nothing but one class extending more than one class.
Multiple Inheritance is basically not supported by many Object Oriented
Programming languages such as Java, Small Talk, C# etc.. (C++ Supports
Multiple Inheritance).
As the Child class has to manage the dependency of more than one Parent class.
But you can achieve multiple inheritance in Java using Interfaces.
7. SUPER KEYWORD
Super keyword
“super” KEYWORD
Example:
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class
default Constructor
Child Class
default Constructor
Even when we add explicitly also it behaves the same way as it did before.
class ParentClass
{
public ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class
default Constructor
Child Class
default Constructor
You can also call the parameterized constructor of the Parent Class.
For example, super(10) will call parameterized constructor of the Parent class.
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor called");
}
ParentClass(int val)
{
System.out.println("Parent Class parameterized Constructor, value: "+val);
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();//Has to be the first statement in the constructor
System.out.println("Child Class default Constructor called");
}
SubClass(int val)
{
super(10);
System.out.println("Child Class parameterized Constructor, value: "+val);
}
public static void main(String args[])
{
//Calling default constructor
SubClass s = new SubClass();
}
}
Output
void disp()
{
System.out.println("Value is : "+val);
}
}
}
Output
Value is : 123
This will call only the val of the sub class only. Without super keyword, you cannot call the val
which is present in the Parent Class.
class ParentClass
{
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;
void disp()
{
System.out.println("Value is : "+super.val);
}
Output
Value is : 999
void disp()
{
System.out.println("Child Class method");
}
void show()
{
disp();
}
public static void main(String args[])
{
}
}
Output:
class ParentClass
{
void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
void disp()
{
System.out.println("Child Class method");
}
void show()
{
//Calling SubClass disp() method disp();
//Calling ParentClass disp() method super.disp();
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.show();
}
}
Output
When there is no method overriding then by default Parent Class disp() method will be called.
class ParentClass
{
public void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
public void show()
{
disp();
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.show();
}
}
Output:
Parent Class method
8. METHOD OVERRIDING
Method overriding
Declaring a method in sub class which is already present in parent class is known as
method overriding.
Overriding is done so that a child class can give its own implementation to a method which
is already provided by the parent class.
In this case the method in parent class is called overridden method and the method in
child class is called overriding method. .
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[])
{ Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
In the above example the call to the disp() method using second object (obj2) is runtime
polymorphism (or dynamic method dispatch).
Note: In dynamic method dispatch the object can call the overriding methods of child class and all
the non-overridden methods of base class but it cannot call the methods which are newly declared in
the child class. In the above example the object obj2 is calling the disp(). However if you try to call
the newMethod() method (which has been newly declared in Demo class) using obj2 then you would
give compilation error with the following message:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: The method xyz() is undefined for the type ABC
Argument list: The argument list of overriding method (method of child class) must match the
Overridden method(the method of parent class). The data types of the arguments and their sequence
should exactly match.
Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the
overridden method of parent class. For e.g. if the Access Modifier of parent class method is public
then the overriding method (child class method ) cannot have private, protected and default Access
modifier,because all of these three access modifiers are more restrictive than public.
For e.g. This is not allowed as child class disp method is more restrictive(protected) than base
class(public)
class MyBaseClass{
public void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends
MyBaseClass{ protected void disp(){
System.out.println("Child class method");
}
public static void main( String args[])
{ MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: Cannot reduce the visibility of the inherited method from MyBaseClass
However this is perfectly valid scenario as public is less restrictive than protected. Same access
modifier is also a valid one.
class
MyBaseClass{ protected
void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends
MyBaseClass{ public void disp(){
System.out.println("Child class method");
}
public static void main( String args[])
{ MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:
Child class method
private, static and final methods cannot be overridden as they are local to the class. However static
methods can be re-declared in the sub class, in this case the sub-class method would act differently
and will have nothing to do with the same static method of parent class.
method (method of child class) can throw unchecked exceptions, regardless of whether the
overridden method(method of parent class) throws any exception or not. However the overriding
method should not throw checked exceptions that are new or broader than the ones declared by the
overridden method.
If a class is extending an abstract class or implementing an interface then it has to override all the
abstract methods unless the class itself is a abstract class.
***************************
A method that is declared as abstract and does not have implementation is known as abstract method.
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes.
If you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.
Example1:
File: TestAbstraction1.java
abstract class Shape{ abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user class Rectangle
extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw(){System.out.println("drawing circle");
}
}
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();
//In real scenario, object is provided through method e.g. getShape() method
s.draw();
}
}
Output:
drawing circle
Example2:
File: TestAbstraction2.java
//example of abstract class that have method body
abstract class Bike{
Bike(){
System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
}
class Honda extends Bike
{
void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run(); obj.changeGear();
}
}
Output:
bike is created running safely..
gear changed
The abstract class can also be used to provide some implementation of the interface.
In such case, the end user may not be forced to override all the methods of the interface.
Example3:
interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A
{
public void c(){System.out.println("I am c");
}
}
class M extends B
{
public void a()
{
System.out.println("I am a");
}
public void b()
{
System.out.println("I am b");
}
public void d()
{
System.out.println("I am d");
}
}
class Test5
{
public static void main(String args[])
{
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}
Output:
I am a I am b I am c I am d
Example1:
$ javac Abstract_Demo.java
$ java Abstract_Demo
Result:18.0
Result:6.0
Result:72.0
Result:2.0
Example 2:
Output:
$ javac AbstractionDemo.java
$ java AbstractionDemo
Result:18.0
Result:6.0
Result:72.0
Result:2.0
Example:
import java.lang.*;
abstract class A
{
abstract void show();
abstract void input();
}
class B extends A
{
void show()
{
System.out.println("hai");
}
void input()
{
System.out.println("hello");
}
}
class A4
{
void calculate()
{
System.out.println("World");
}
public static void main(String s[])
{
B a = new B();
a.show();
a.input();
}
}
Example 2:
abstract class A
{
abstract void method1();
abstract void method2();
}
abstract class B extends A
{
void method1()
{
System.out.println("Hello");
}
abstract void method2();
}
class C extends B
{
void method2()
{
System.out.println("World");
}
public static void main(String s[])
{
C c=new C();
c.method1();
c.method2();
}
}
***************
// base class
abstract class
Shape
{
private double width;
}
//derived class two
class Square extends Shape
{
// Square class parameterized constructor
public Square(double side)
{
// calling Shape class constructor
super(side, side);
}
// Driver class
public class Test
{
public static void main(String[] args)
{
// creating Rectangle object
Shape s1 = new Rectangle(10, 20);
//getting area of s1
System.out.println("area of s1 : "+ s1.getArea());
//getting area of s2
System.out.println("area of s2 : "+ s2.getArea());
}
}
1) Introduction to
in Java?
It helps organize your classes into a folder structure and make it easy to locate and use them.
Each package in Java has its unique name and organizes its classes and interfaces into
a separate namespace, or name group.
Although interfaces and classes with the same name cannot appear in the same package, they
can appear in different packages.
This is possible by assigning a separate namespace to each package.
Definition: A package is a collection of related types providing access protection and name space
management.
Creating a Package
To create a package, put a type (class, interface, enum, or annotation) in it.
To do this, put a package statement at the top of the source file in which the type
is defined.
Note that types refers to classes, interfaces, enums, and annotations.
The types that are part of the Java platform are members of various packages that bundle
classes by function: fundamental classes are in java.lang, classes for reading and writing
(input and output) are in java.io, and so on.
You can put your types in packages too.
Types of Packages
a) Standard Packages
a) Standard Packages
The packages that are built-in in the java are called standard or built-in packages.
The following figure gives an outline on major standard packages available for
users:
Need of packages:
Suppose you write a group of classes that represents a collection of graphic objects, such
as circles, rectangles, lines, and points.
You also write an interface, Draggable, that classes implement if they can be dragged with
the mouse by the user.
You should bundle these classes and the interface in a package for several reasons, including the
following:
You and other programmers can easily determine that these types are related.
You and other programmers know where to find types that can provide graphics-
related functions.
The names of your types won't conflict with the type names in other packages because
the package creates a new namespace.
You can allow types within the package to have unrestricted access to one another yet
still restrict access for types outside the the package.
The scope of the package statement is the entire source file, so all classes, interfaces,
enums, and annotations defined in class1 and class2 are also members of the
pack package.
If you put multiple classes in a single source file, only one can be public, and it must share
the name of the source file's base name.
Only public package members are accessible from outside of the package.
If you do not use a package statement, your type ends up in the default package, which
is a package that has no name.
Generally speaking, the default package is only for small or temporary applications or when
you are just beginning the development process. Otherwise, classes, enums, and
annotations belong in named packages.
Naming a Package
With programmers worldwide writing classes, interfaces, enums, and annotations using
the Java programming language, it is likely that two programmers will use the same name
for two different classes.
In fact, the previous example does just that: It defines a Rectangle class when there
is already a Rectangle class in the java.awt package.
Still, the compiler allows both classes to have the same name. Why? Because they are in
different packages, and the fully qualified name of each class includes the package name.
That is, the fully qualified name of the Rectangle class in the graphics package
is graphics.Rectangle, and the fully qualified name of the Rectangle class in
the java.awt package is java.awt.Rectangle.
Using Package Members
Only public package members are accessible outside the package in which they are defined.
To use a public package member from outside its package, you must do one or more of the
following:
Syntax:-
package nameOfPackage;
Let's study package with an example. We define a class and object and later compile this it in our
package p1. After compilation, we execute the code as a java package.
Here,
1. To put a class into a package, at the first line of code define package p1
2. Create a class c1
3. Defining a method m1 which prints a line.
4. Defining the main method
5. Creating an object of class c1
6. Calling method m1
The compilation is completed. A class file c1 is created. However, no package is created? Next step
has the solution
Step 4) Now we have to create a package, use the command
javac –d . demo.java
Step 5) When you execute the code, it creates a package p1. When you open the java package p1
inside you will see the c1.class file.
javac –d .. demo.java
Here ".." indicates the parent directory. In our case file will be saved in parent directory which is C
Drive
File saved in parent directory when above code is executed.
Step 7) Now let's say you want to create a sub package p2 within our existing java package p1. Then
we will modify our code as
package p1.p2
As seen in below screenshot, it creates a sub-package p2 having class c1 inside the package.
Step 9) To execute the code mention the fully qualified name of the class i.e. the package name
followed by the sub-package name followed by the class name -
java p1.p2.c1
This is how the package is executed and gives the output as "m1 of c1" from the code file.
***********************
13. PACKAGES AND MEMBER ACCESS
Definition: A package is a collection of related types providing access protection and name space
management.
The types that are part of the Java platform are members of various packages that
bundle classes by function: fundamental classes are in java.lang, classes for reading and
writing (input and output) are in java.io, and so on.
You can put your types in packages too.
Need of packages:
Suppose you write a group of classes that represents a collection of graphic objects, such
as circles, rectangles, lines, and points.
You also write an interface, Draggable, that classes implement if they can be dragged with the
mouse by the user.
You should bundle these classes and the interface in a package for several reasons, including the
following:
You and other programmers can easily determine that these types are related.
You and other programmers know where to find types that can provide graphics-related
functions.
The names of your types won't conflict with the type names in other packages because
the package creates a new namespace.
You can allow types within the package to have unrestricted access to one another yet still
restrict access for types outside the the package.
Creating a Package
To create a package, put a type (class, interface, enum, or annotation) in it.
To do this, put a package statement at the top of the source file in which the type is defined.
For example, the following code appears in the Circle.java source file and puts the Circle class in the
graphics package.
package graphics;
You must include a package statement at the top of every source file that defines a class or an
interface that is to be a member of the graphics package.
So, you would also include the statement in Rectangle.java and so on.
package graphics;
The scope of the package statement is the entire source file, so all classes, interfaces, enums,
and annotations defined in Circle.java and Rectangle.java are also members of the graphics
package.
If you put multiple classes in a single source file, only one can be public, and it must share the
name of the source file's base name.
Only public package members are accessible from outside of the package.
If you do not use a package statement, your type ends up in the default package, which is a
package that has no name.
Generally speaking, the default package is only for small or temporary applications or when
you are just beginning the development process. Otherwise, classes, enums, and
annotations belong in named packages.
Naming a Package
With programmers worldwide writing classes, interfaces, enums, and annotations using the
Java programming language, it is likely that two programmers will use the same name for two
different classes.
In fact, the previous example does just that: It defines a Rectangle class when there is already
a Rectangle class in the java.awt package.
Still, the compiler allows both classes to have the same name. Why? Because they are in
different packages, and the fully qualified name of each class includes the package name.
That is, the fully qualified name of the Rectangle class in the graphics package is
graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt
package is java.awt.Rectangle.
To use a public package member from outside its package, you must do one or more of the
following:
Here is the qualified name for the Rectangle class declared in the graphics package in the previous
example.
graphics.Rectangle
You'll find that using long names is all right for one-shot uses; however, you'd probably get
annoyed if you had to write graphics.Rectangle again and again.
Also, the code would get messy and difficult to read. In such cases, you can import
the member instead.
*************
Here's how you would import the Circle class from the graphics package created in the previous
section.
import graphics.Circle;
Now you can refer to the Circle class by its simple name.
Circle myCircle = new Circle();
This approach works well if you use just a few members from the graphics package. But, if you use
many types from a package, you can import the entire package.
import graphics.*;
Now you can refer to any class or interface in the graphics package by its short name.
The asterisk in the import statement can be used only to specify all the classes within
a package, as shown here.
It cannot be used to match a subset of the classes in a package.
For example, the following does not match all the classes in the graphics package that begin with A.
import graphics.A*; //does not work
Instead, it generates a compiler error. With the import statement, you generally import only a single
package member or an entire package.
Note:
For convenience, the Java compiler automatically imports three entire packages: (1) the default
package (the package with no name), (2) the java.lang package, and (3) the current package by
default.
(4) Packages aren't hierarchical. For example, importing java.util.* doesn't allow you to refer to the
Pattern class as regex.Pattern.
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).
Output:Welcome to package
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.
INTERFACE IN 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 and multiple inheritance.
Interface is declared by using interface keyword.
It provides total abstraction; means all the methods in interface are declared with empty
body and are public and all fields are public, staticand final by default.
A class that implement interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>
{
Example:
interfaceprintable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Output:
drawing circle
Example:
Interface Printable
{ void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void
show(){System.out.println("Welcome");}
obj.show();
}}
Output:
Hell
o
Wel
com
e
}
}
15) Variable names conflicts can be resolved
by interfacename. interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implements A,B
{
public static void Main(String args[])
{
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}
************************