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

Chapter 4 - OOP Concepts (4)

Here is OOP concept material use it.

Uploaded by

jamsibro140
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Chapter 4 - OOP Concepts (4)

Here is OOP concept material use it.

Uploaded by

jamsibro140
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter Four: Object Oriented Concepts April 10, 2023

Chapter Four:
Object Oriented Concepts
Objectives:
At the end of this chapter you will be able to understand and practice the following OO concepts
programmatically.
 Inheritance
 Polymorphism
 Encapsulation
 Method overloading and overriding
 Packages and interfaces

4.1. Encapsulation
Question: What is a class? How is it constructed in Java?

If you answer the above questions, it is easier for you to understand what encapsulation is.
Encapsulation is the concept and it becomes a class programmatically. Encapsulation is a concept of
putting both data and code into a capsule. In other words instance variables and methods are written
inside a container. This container is the class that you already read it in the previous chapter.

Encapsulation gives us advantages. The core concept that it gives us is information hiding. Information
hiding is one of the key features of object oriented programming. It is the concept of restricting/allowing
the resources of an object. An object’s instance variables and methods can be set to be not accessed by
other objects. Only those variables and methods that are set to be accessed by others are available.

Everything said above can be demonstrated by the following example.


class A{ class B{
private int x; private float z;
public void setX(int y){ public void setZ(int a){
x = y; z = a;
} }
} }
Class A cannot access what is private in B and vice versa. So the variable x cannot be accessed by B.
But the method setX() can be used by class B. This is accomplished using access modifiers called
private, public and protected. There is an additional access level called package level which has no a
key word (access modifier). Access modifiers will be discussed in more detail later in this chapter.

4.2. Inheritance
Inheritance allows the hierarchical classification of objects. Using inheritance, you can create a general
class that defines traits common to a set of related items. This class can then be inherited by other, more
specific classes, each adding those things that are unique to it. A class that is inherited is called a
superclass. The class that does the inheriting is called a subclass. A subclass is a specialized version of a
superclass. It inherits all of the members defined by the superclass and adds its own, unique elements.

Compiled by: Tizazu B Injibara University Page 1 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
The following diagram illustrates inheritance with hierarchical classification of Injibara University’s
community.

InjibaraComminity

Staff Student

AdminStaff AcademicStaff Regular Extension

InjibaraComminity is the superclass and it defines the common data and code that will apply to all the
subclasses, i.e., all the classes down the hierarchy. Staff class inherits the data and code defined by
InjibaraComminity and it adds the data and code that are specific to staffs. The Staff class defines those
things that are common to both admin and academic staff. AdminStaff inherits from Staff directly and
from InjibaraComminity indirectly. The same concept applies to the Student class and its subclasses.
Note:- The level of the hierarchy is not limited. For example, academic staff can further be classified
into faculties; technology, science, business and economics, etc. The level is decided by us. If we
believe this is enough as a solution, we can stop.
In java, multiple inheritance is not allowed. In other words a class cannot have two or more direct
superclasses. AdminStaff has one direct superclass, that is, the Staff class. It has an indirect superclass
which is the InjibaraComminity class. So a class is not allowed only to have on direct superclass but it
can have many indirect superclasses.
The syntax of creating a subclass is as follows:
class SubclassName extends SuperclassName{
//instance variables
//methods
}
The keyword extends is used to define a relationship of inheritance. SubclassName is the name of the
subclass and SuperclassName is the name of the superclass.
Using this syntax, we can create the programmatic equivalent of the above diagram as follows. You
must carefully examine the example.

Compiled by: Tizazu B Injibara University Page 2 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
class InjibaraComminity{ class AdminStaff extends Staff{
String name; String empType;
String getName(){ String getEmpType(){
return name; return empType;
} }
} }
class Staff extends InjibaraComminity { class AcademicStaff extends Staff{
float salary; String rank;
float getSalary(){ String getRank(){
return salary; return rank;
} }
} }
class Student extends InjibaraComminity { class Regular extends Student{
float cgpa; float costSharing;
float getCgpa(){ float getCostSharing(){
return cgpa; return costSharing;
} }
} }
class Extension extends Student{
float semesterPayment;
float getSemesterPayment(){
return semesterPayment;
}
}
Questions:
What are the members of the Staff class? What are the members of the Regular class?

4.2.1. Member Access


We have discussed that a subclass inherits all the members of its superclasses. However, those members
of a superclass that are declared as private cannot be inherited by the subclasses. The following
example demonstrates this.
class A{
int a, b;  The class B is the subclass of the class A. Some of the
private int c; members of class A are declared private. So these
void meth1(){ private members of the class A cannot be inherited by
class B.
}  The variables a and b have package access and the
private int meth2(){ method meth1 has package access.
return 0;  As a result, class B inherits the instance variables a and
} b, and the method meth1 only. The variable c and the
} method meth2 cannot be inherited by.
class B extends A{
float x;
int y;
float fun(){
meth1();
return a+b;
}
}

Compiled by: Tizazu B Injibara University Page 3 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
How does the subclasses use the members inherited from their subclasses? A subclass uses these
members directly; like in fun() method. The variables a and b are inherited from A. meth1() is also
inherited.

4.2.2. Reference Variable


Since inheritance defines is-a relationship, that is, a subclass is a type of the superclass, the reference
variable of the superclass can be assigned a reference of any subclass derived from that superclass. This
situation is called Upcasting. But a subclass reference variable can’t refer to the superclass object.
Considering the InjibaraComminity inheritance hierarchy, indentify which of the following are correct.
InjibaraComminity y wc;
Student s;
Regular r = new Regular();
Staff st = new Staff();
AdminStaff ad1, ad2 = new AdminStaff();
s = r;
wc = ad2;
ad1 = st;
wc = s;
wc = st;

4.2.3. How are Constructors Called?


In a class hierarchy, constructors are called in order of derivation, from the superclass to subclass. The
example below demonstrates how the constructors are called.
class A{
A(){
System.out.println("In class A");
} When the statement A a = A(); is executed, the
} constructor of A is called.
class B extends A{
B(){ When the statement B b = B(); is executed, the
System.out.println("In class B"); constructor of A is called first, then the constructor of B
} is called.
}
class C extends B{ When the statement C c = C(); is executed, the
C(){ constructor of A is called first, next the constructor of B
System.out.println("In class C"); is called and finally the constructor of C is called.
}
} Question
class Main{ Based on the description, write down the output of the
public static void main(String args[]){ program.
A a = new A();
System.out.println("----------------");
B b = new B();
System.out.println("----------------");
C c = new C();
}
}

Compiled by: Tizazu B Injibara University Page 4 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
4.2.4. Using the super Keyword
The keyword super has two uses; to call the constructor of the superclass and to access the hidden
members of the superclass. Calling the superclass constructor is needed when the default constructor of
the superclass is not available or when the superclass has overloaded constructors to choose from or
when we need to initialize the private variables of the superclass or when we want to use super. The
super keyword must be the first statement in a constructor if it is used. The syntax is as follows:
super(); //by default this is called if we didn’t specify one.
super(argument_list);//this is used to call constructors with arguments
The example shown below illustrates the use of super to call the superclass’ constructors.
class A{
A(){ The constructor B() do not use super so the superclass’
System.out.println("In A"); A() constructor is called by default.
}
A(int x){ In B(String b) constructor, super() calls the superclass’
System.out.println(x); A() constructor.
}
A(int a, float z){ In B(int y) constructor, super(y, 3.3f) calls the
System.out.println(a + " " + z); corresponding constructor of A, that is the one with two
} } arguments with the first being int and the second being
class B extends A{ float. Means the constructor A(int a, float z) is called.
B(){
System.out.println("In B");
} Qestion
B(String b){ Based on the description, write down the output of the
super(); program.
System.out.println(b);
}
B(int y){
super(y,3.3f);
}
}
class Main{
public static void main(String args[]){
B b1 = new B();
B b2 = new B("Test");
B b3 = new B(10);
}
}
The second use of the super keyword is to access hidden members of the superclass. When a superclass’
instance variable and a subclass’ instance variable has same name, the subclass variable hides the
superclass variable. In other words, using this name inside the subclass always refers to the subclass’
variable. The same is true for methods when method overriding is used. Method overriding is discussed
later in this chapter. The syntax is as follows:
super.var_name;
super.meth_name(arg_list);

Compiled by: Tizazu B Injibara University Page 5 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
class A{
int x, y;
A(){
x = 10;
y = 25;
}
void show(){
System.out.println("A's show method");
}
}
class B extends A{
float x;
double z;
B(){ The show(); call inside show2 method calls the
x = 13; show() method of the subclass. The super.show()
z = 33.66; calls the superclass’ show() method.
}
void show(){ In the constructor of B and in the show() method
System.out.print(x + " " + z + " "); of B, the x refers to only the instance variable of
System.out.println(super.x + " " + y); B. To access the superclass’ x variable, super.x is
} used inside the show() method of B.
void show2(){
show(); Question
super.show(); Write down the exact output of the example?
}
}
class Main{
public static void main(String ar[]){
B b = new B();
b.show2();
}
}

4.2.5. Method Overriding


In a class hierarchy, 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. If you need
to call this hidden method from within the subclass, you must use the super keyword as described above.
Method overriding occurs only when the names and the type signatures of the two methods are identical.
If they are not, then the two methods are simply overloaded.
Method overriding is important when the subclass needs its own implementation of a method inherited
form its superclass. This is because the superclass’ method implementation may not exactly work for the
subclass. Another use of method overriding in conjunction with inheritance is to support runtime
polymorphism. Static or compile time polymorphism is supported by method overloading.
Polymorphism is detailed next in this chapter.
The Example below demonstrates method overriding.

Compiled by: Tizazu B Injibara University Page 6 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
class Example1{
void show(int x){
System.out.println(x);
}
int add(int a, int b){
return a+b;
}
int mult(int z, int w){
return z*w;
}
}
class Example2 extends Example1{
void show(int n){
System.out.println(n);
}
int add(int i, int j){
System.out.println(super.add(i, j+5));//calls Example1's method
return i+j;
}
float mult(float z, float w){
return z*w;
}
}
class Main{
public static void main(String a[]){
Example1 e1 = new Example1();
e1.show(12);//calls Example1's method
System.out.println(e1.add(20,40));//calls Example1's method
System.out.println(e1.mult(2,6));//calls Example1's method
Example2 e2 = new Example2();
e2.show(65);//calls Example2's method
System.out.println(e2.add(15,100));//calls Example2's method
System.out.println(e2.mult(4,5));//calls Example1's method
System.out.println(e2.mult(10.5f,20.0f)); //calls Example2's method
}
}

4.3. Polymorphism
As you may remember polymorphism is the concept using a single interface to represent multiple
different actions. Compile time polymorphism is supported by method overloading. Runtime
polymorphism is realized through method overriding.
Dynamic, runtime polymorphism is one of the most powerful mechanisms that object oriented design
brings to bear on code reuse and robustness.

4.3.1. Dynamic Method Dispatch


Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
runtime, rather than compile time.
A superclass reference variable can refer to a subclass object. When an overridden method is called
through a superclass reference, java determines which version of that method is executed based upon the

Compiled by: Tizazu B Injibara University Page 7 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
type of the object being referred to at the time the call occurs. Thus the determination is made at
runtime. When different types of objects are referred to, different versions of an overridden method will
be called. In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed. Therefore, if a
superclass contains a method that is overridden by a subclass, then when different types of objects are
referred to through a superclass reference variable, different versions of the method are executed. In the
following example we will see how polymorphism is implemented.
class Shape{
float area(float height, float width){
return 0.0f; The reference variable s is of type Shape.
}
} The first call to s.area() calls the method found in the
class Rectangle extends Shape{ Shape class because the object referenced by s is of
float area(float h, float w){ type Shape.
return h*w;
} The second call to s.area() calls the method found in the
} Rectangle class because the object referenced by s is of
class Triangle extends Shape{ type Rectangle even if the type of s is Shape.
float area(float h, float w){
return (h*w)/2; The third call to s.area() calls the method found in the
} Triangle class because the object referenced by s is of
} type Triangle even if the type of s is Shape.
class PolymorphismExample{
public static void main(String a[]){ Question:
Shape s = new Shape(); Write down the output of the program exactly as seen
System.out.println(s.area(5,10)); on the computer screen.
s = new Rectangle();
System.out.println(s.area(5,10));
s = new Triangle();
System.out.println(s.area(5,10));
}
}

4.4. Abstract Class


There are situations in which you will want to define a superclass that declares the structure of a given
abstraction without providing a complete implementation of every method. That is, sometimes you will
want to create a superclass that only defines a generalized form that will be shared by all of its
subclasses, leaving it to each subclass to fill in the details. One way this situation can occure is when a
superclass is unable to create a meaningful implementation for a method. Java’s solution to this is the
abstract method.
An abstract method is a method that must be overridden by a subclass. You can require that certain
methods be overridden by subclasses by specifying the abstract modifier. These abstract methods are
sometimes referred to as subclasser responsibility because they have no implementation specified in the
superclass. To declare an abstract method, use the following general form:
abstract type method_name(parameter-list);
Any class that contains one or more abstract methods must also be declared abstract. The following is
the general syntax for declaring abstract classes.
Compiled by: Tizazu B Injibara University Page 8 of 16
Chapter Four: Object Oriented Concepts April 10, 2023
abstract class Class-Name{
//body
}
Abstract classes can contain other non abstract methods, variables, constructors, etc. An object of an
abstract class cannot be created. Constructors cannot be declared as abstract. Static methods cannot be
declared as static. Any subclass of an abstract class must either implement all of the abstract methods in
the superclass, or be declared abstract itself.
Using abstract classes and methods is demonstrated below.
abstract class Shape{
float height, width;
Shape(float h, float w){
height = h; width = w;
}
void showDimension(){
System.out.println("Height: " + height + " Width: " + width);
}
abstract float area();
/*subclasses of Shape must override the method area()*/
}
class Rectangle extends Shape{
Rectangle(float a, float b){
super(a,b);
}
//Rectangle is the subclass of Shape so it must override area() otherwise must be declared abstract
float area(){
return height*width;
}
}
class Triangle extends Shape{
Triangle(float a, float b){
super(a,b);
}
//Triangle is the subclass of Shape so it must override area() otherwise must be declared abstract
float area(){
return (height*width)/2;
}
}
class Main{
public static void main(String []a){
Shape s;
//s = new Shape(); error - an object of an abstract class can not be created
s = new Rectangle(12,10);
s.showDimension();
System.out.println(s.area());
s = new Triangle(8,10);
s.showDimension();
System.out.println(s.area());
}}
Question:
Put the output of the example program exactly as seen on the computer screen.

Compiled by: Tizazu B Injibara University Page 9 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
4.5. Using the final Keyword
The final keyword has three uses in java. Obviously, you remember the use of the final keyword to
declare constant variables. The second use is to prevent method overriding. The third is to prevent
inheritance. The latter two uses are discussed here.
Sometimes you may need methods of a superclass to be not overridden by its subclasses. To do so,
precede the method with the final keyword. The general syntax is as follows:
final type method-name(parameter-list){
//method body
}
A final method cannot be abstract since final and abstract are contradictory. The abstract is used to
enforce overriding; on the contrary, the final is used to avoid overriding. However, an abstract class can
contain both final methods and abstract methods.
class A{
final void method1(){
System.out.println("This is a final ");
System.out.println("it cannot be overridden ");
System.out.println("by the subclasses of A");
}
void method2(){
System.out.println("This may or may not be overridden ");
System.out.println(" by the subclasses of A");
}
}
class B extends A{
//B can not override method1() since this method is declared
//final
//B may or may not override method2(). it is our decision
}
Sometimes you need a class that must not be a superclass. But it may be a subclass of another
superclass. A final class cannot contain an abstract method. Since a final class cannot be a superclass, it
is none sense to make its methods final even if you can. To realize this, you only need to precede the
class with the final key word. A final class cannot be abstract too.
final class Class-Name{
//body
}
final class A{
void show(){
System.out.println("This is a show method");
}
final void show1(){ //none sense but syntactically correct
System.out.println("Another but it is final");
}
}
class B extends A{ //error b/c A is final it cannot be subclassed
}

Compiled by: Tizazu B Injibara University Page 10 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
4.6. The Object class
Object class is a special class in java. This class is by default the superclass of all other classes defined
in your program. This means a reference variable of the Object class can refer to an object of any other
class as discussed before that a superclass reference variable can refer to an object of any of its
subclasses. There are some methods available in the object class. Many of these methods are inherited
by any other class. You need to read about these methods.

4.7. Interface
An interface is similar to a class and it is completely abstract. An interface has no instance variables. To
declare an interface, use the keyword interface.
interface Interface_name{
type var1 = value1;
type var2 = value2;
.
type varN = valueN;
type method_name1(parameter-list);
type method_name2(parameter-list);
.
type method_nameN(parameter-list);
}
All the variables of an interface are static and final by default. All the methods of an interface are
abstract by default. Both the methods and variable are also public. The interface itself can be declared
public so that it can be accessed by all part of your program. If public is not specified, the default access
is applied, as a result, the interface can only be accessed inside the package it is declared. Packages are
discussed later in this chapter.
An interface is useless unless it is implemented by a class. A class can implement any number of
interfaces and an interface can be implemented by any number of classes. When we say a class
implements an interface, it is must for the class to provide implementation (body) for each and every
method of the interface. If one of the methods is left unimplemented by the class, the class itself must be
declared as abstract; otherwise it is a compiler error. One more thing to add, all the implemented
methods in the implementer class must be declared as public; otherwise the compiler will issue an error.
class classname [extends superclass] [implements interface1, interface2, ….., interfaceN] {
//class body must provide code for each and every method of the interfaces
}
A reference variable of type interface can be declared. This reference variable can refer to the object of
any of the classes that implement the interface by which a reference variable is created. This is possible
since the interface can be considered as a superclass for those classes that implement the interface
directly or indirectly. On the other hand, it is not allowed to create object of an interface.
If a reference variable of an interface can refer to objects of any of the classes implementing the
interface, using interfaces, you can still realize polymorphism. Polymorphism came to practice through
the use of inheritance, method overriding and upcasting. All these things are also available when
implementing interfaces.
The examples below describe all the concepts discussed here.

Compiled by: Tizazu B Injibara University Page 11 of 16


Chapter Four: Object Oriented Concepts April 10, 2023

interface Example{
int x = 10; The class A provides the correct implementation for all
int add(int a, int b); the methods of the interface so that there is no any
float mult(float y, float z); problem.
}
class A implements Example{ The class B leaves the mult() method unimplemented.
public int add(int i, int j){ As a result a compiler error will appear. To fix this
return i+j; problem, either class B must be declared abstract or
} class B must provide implementation (may be empty
public float mult(float y, float z){ body if it can’t provide or may not need the method at
return y*z; all) for mult() method.
}
} Question:
class B implements Example{ Based on the given explanation, correct the error found
public int add(int c, int d){ in class B. Try both solutions.
return c+d;
}
}

Another example:
interface Example{
int x = 10;
int add(int a, int b);
float mult(float y, float z);
}
class A implements Example{
public int add(int i, int j){
return i+j;
}
public float mult(float y, float z){
return y*z;
}}
class B implements Example{
public int add(int c, int d){
return c+d;
}
public float mult(float m, float n){
return m*n;
}}
class Main{
public static void main(String []argument){
Example e;
//e = new Example(); this is incorrect
e = new A();
System.out.println(e.add(20, 25) + " " + e.mult(2,8));
e = new B();
System.out.println(e.add(20, 25) + " " + e.mult(2,8));
}}

Compiled by: Tizazu B Injibara University Page 12 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
An interface can also extend other interface. This is done using the extends keyword. The syntax is as
follows:
interface Interface1 extends Interface2{
//interface body
}
interface A{ A class implementing interface A has the duty of
int meth1(); implementing both meth1() and meth2(); otherwise, if one is
void meth2(); left unimplemented, it must be abstract.
} A class implementing interface B has the duty of
interface B extends A{ implementing meth1(), meth2() and meth3(); otherwise, if
float meth3(); one is left unimplemented, it must be abstract.
//since B extends A, B's methods Question:
//are the meth3 and the methods of A Based on the description given, create a class called D that
//that are meth1() and meth2() implements interface B.
}

4.8. Package
In the examples used up to this time, the name of each example class was taken from the same name
space. This means that a unique name had to be used for each class to avoid name collisions. After a
while, without some way to manage the name space, you could run out of convenient, descriptive names
for individual classes. You also need some way to be assured that the name you choose for a class will
be reasonably unique and not collide with class name chosen by other programmers. (Imagine a small
group of programmers fighting over who gets to use the name “Foobar” as a class name. Or, imagine the
entire internet community arguing over who first named a class “Espresso”.) Thankfully, java provides a
mechanism for partitioning the class name space into more manageable chunks. This mechanism is the
package.
The package is both a naming and a visibility control mechanism. You can define classes inside a
package that are not accessible by code outside that package. You can also define class members that are
exposed only to other members of the same package. This allows your classes to have intimate
knowledge of each other, but not expose that knowledge to the rest of the world.

4.8.1. Defining a Package


A package is created using the package keyword. The package statement must be the first statement in
the file and it must be written only once. Any class declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default package, which has no name.
This is why you don’t have to worry about packages before now. While the default package is fine for
short, sample programs, it is inadequate for real applications. The general syntax is as follows:
package packagename;
After the java program is compiled, the .class files will be stored in a directory named after the package
name. That is, the name of the package in which the classes belong and the name of the folder the
corresponding .class files are stored must be exactly the same.
More than one java source files can include the same package statement. Many real-world packages are
spread across many files.

Compiled by: Tizazu B Injibara University Page 13 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
A hierarchy of packages can be created by separating each package name from the one above it by use
of a period (.). The general form is:
package pkg1[.pkg2[.pkg3[…]]];
The package hierarchy must be reflected in the file system of your java development system. For
example the package package java.awt.image; must be stored in a directory named java\awt\image\ in
windows environment.

4.8.2. Access Protection


There are three keywords to specify access control; private, protected and public. The private members
of a class are granted access to other members of that same class. The protected members of a class are
granted access to the other members of the class that contains them, to subclasses found in any package
and to non-subclasses found in the same package with the container class. The public members of a class
are granted access to the other members of the class that contains them and to any subclass and non-
subclasses found in any package.
There one additional access level in java which is called package level access. This access has no
keyword. If you specify a class, a method or an instance variable without using one of the above
keywords, the default package access is applied. The package access is the default if none of the
keywords are used. The package level members of a class are granted access to the other members of the
class that contains them and any class that is found in the same package with the container class.
Access protection is not only for the members of the classes but also for the classes itself. A class can be
specified either using public or package level access. However, all the access levels can be applied for
inner classes. The same is true for interfaces.
Note that a public non-inner class must be saved in a file named after the class itself. So, no two non-
inner public classes can be put in one file. The same applies for interfaces.
The following table summarizes how members of a class can be access when there are more than one
package.
Private No-modifier Protected Public
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes

4.8.3. Importing Packages


Java includes the import statement to bring certain classes or entire classes of a package into visibility to
other packages. Assume we have two packages called pkg1 and pkg2. If you need to access the classes
of pkg2 inside pkg1, you must use the import statement to inform java that those classes are found in
pkg2. The import statement has two forms. One used to import a single class and the other to import all
the classes of the package. The syntaxes are as follows respectively.
import packagename.classname; //to import a single class
import packagename.*;//to import all the classes

Compiled by: Tizazu B Injibara University Page 14 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
You need to be careful that all the import statements must come next to the package statement if there
exists. You remember that the package statement must be the first statement in a java file if there exists.

4.8.4. Package Example


The example below demonstrates a java program that has three packages. It shows how to import.
package edu.wldu.engineering; This program must be saved in a file called A.java
public class A{ since the class A is public.
public void show(){ All the classes in this file are in a package called
System.out.println("Eng class a"); edu.wldu.engineering.
} Since no classes form other packages are needed,
} import statement is not used.
package edu.wldu.engineering; This program must be saved in a file called D.java
public class D{ since the class D is public.
public void method(){ The classes in this file are also in engineering package.
System.out.println("eng class D");
}
}
package edu.wldu.fbe; This program must be saved in a file called B.java since
import edu.wldu.engineering.A; the class B is public.
public class B{ All the classes in this file are in a package called
public void display(){ edu.wldu.fbe.
System.out.println("fbe class b"); Since the class A from engineering package is needed
A a = new A(); here, import statement is used to import the class A.
a.show();
C c = new C();
c.meth();
}
}
class C{
void meth(){
System.out.println("fbe class C");
}
}
package edu.wldu.main; This can be saved in any name you choose. Let us save
import edu.wldu.engineering.*; it with pkgexample.java.
import edu.wldu.fbe.*; All the classes in this file are in a package called
class Main{ edu.wldu.main.
public static void main(String ar[]){ Since classes form other packages are needed, import
A a = new A(); statement is used to import all the classes from each
B b = new B(); package except the class C of fbe because it is access
a.show(); level is package.
b.display();
D d = new D();
d.method();
}
}

Compiled by: Tizazu B Injibara University Page 15 of 16


Chapter Four: Object Oriented Concepts April 10, 2023
4.8.5. How can you compile and run a java program with packages?
There are three options to compile and run java programs that are compartmentalized using packages.
The first option is to compile and run the programs from the working directory. In this way use the javac
–d .\ *.java command accomplishes the objective. The –d means where the files are found and the next
argument specifies the directory; which in this case is the working directory (.\). The last argument
specifies the java files. Use the java command with the fully qualified name of the main class to run the
program. A fully qualified name is a dot separated name including the package hierarchy. For example
the fully qualified name of A is edu.wldu.engineering.A.
Use the following commands to compile and run the above given program. First put all the files in one
folder. Then on the command prompt, make this folder your working directory.
javac –d .\ *.java
java edu.wldu.main.Main
After compiling, see the folder where your files are. New folder is created based on the package
hierarchy.
The second option to compile and run java programs with packages is to set the CLASSPATH of the
systems environment variable. You know how to set environment variable in windows operating system.
To run the program using the third option, the class paths are specified as an argument for the java
command as follows:
java –cp thepath themainclass
Here –cp specifies the next argument is a path to the classes. The next argument thepath specifies the
path. The third is the name of the file.

Compiled by: Tizazu B Injibara University Page 16 of 16

You might also like