OOP thr Java-UNIT 2
OOP thr Java-UNIT 2
UNIT-II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass,
subtype, substitutability, forms of inheritance specialization, specification, construction,
extension, limitation, combination, benefits of inheritance, costs of inheritance. Member
access rules, super uses, using final with inheritance, polymorphism- method overriding,
abstract classes, the Object class. Defining, Creating and Accessing a Package, Understanding
CLASSPATH, importing packages, differences between classes and interfaces, defining an
interface, implementing interface, applying interfaces, variables in interface and extending
interfaces. Exploring java.io.
Inheritance
Inheritance is one of the corner stones of Object-oriented programming. Because it
allows hierarchical classifications. In terminology of java, a class that is inherited is
called a super class. The class that does the inheriting is called a subclass. Therefore,
a subclass is a specialized version of super class. It inherits all of the instance
variables and methods defined by the super class and adds its own, unique
elements.
Hierarchical abstractions
A powerful way to manage abstraction is through the use of hierarchical classification. This
allows to break the complex systems into manageable pieces.
For example, a car is a single object for outside but the car consists of several subsystems
such as steering, breaks, sound system, seat belts etc. Again, the sound system consists of
radio, DVD player etc. Here we manage the complexity of a car system through the use of
hierarchical classification. Here everything we view in this world is an object. The topmost
hierarchy for every object is material object.
Base class: Suppose in the above example, car is the base class. and the sub classes are
steering, breaks, engine etc. The behaviour of the child class is always an extension of the
properties of the associated with the parent class.
Subclass: Consider the relationship associated with the parent class and subclass.
Instances of a sub class must possess all the data areas associated with the parent
class.
Instances of a sub-class must implement through inheritance at least some or all
functionalities defined for the parent class.
Thus, an instance of a child class can mime the behaviour of the parent class and
should be indistinguishable from the instance of parent class if substituted in similar
situation. This creates a problem because we use so many forms of inheritance. To
solve this, we use principle of substitutability.
Substitutability: “The principle of substitutability” says that if we have two classes ‘A’
and ‘B’ such that class B is sub-class of A class, it should be possible to substitute instances of
class B for instance of class A in any situation with no observable effect.
Subtype: The term subtype often refers to a subclass relationship in which the principle of
substitutability is maintained. Statically typed languages (C++) place much more emphasis
on principle of substitutability than dynamically typed languages (Small Talk)
The reason for this is the statically typed languages tend to characterize objects by their class
and dynamically typed languages tend to characterize by behaviour. That is the subtype us
determined in statically typed languages by their class and dynamically typed languages by
their behaviour.
The general form of a class declaration that inherits a superclass is shown here:
The following program creates a superclass called A and a subclass called B. Notice
how the keyword extends is used to create a subclass of A.
Example
// A simple example of inheritance. Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
P.Ramesh, Assistant Professor,AIML Dept, TKREC 2
OOP through Java UNIT-2
{
A superObj = new A();
B subObj = new B();
OUTPUT
D:\TKREC\Java>java SimpleInheritance
Contents of superObj:
i and j: 10 20
Contents of subObj:
i and j: 7 8
k: 9
Types of Inheritance: When deriving a class from a base class, the base class
may be inherited through public, protected or private inheritance.
Creating Child Class in java: In java, we use the keyword extends to create a
child class. Inheritance represents the IS-A relationship.
The following syntax used to create a child class in java.
Syntax
class <ChildClassName> extends <ParentClassName>
{
//Implementation of child class
}
In a java programming language, a class extends only one class. Extending
multipleclasses is not allowed in java.
P.Ramesh, Assistant Professor,AIML Dept, TKREC 3
OOP through Java UNIT-2
Single inheritance: In a class hierarchy when a child has one and only one
parent and parent has one only child, that inheritance is said to be single
inheritance.
Example
class Student
{
int rollno;
void getNo(int no)
{
rollno=no;
}
void putNo()
{
System.out.println("rollno="+rollno);
}
}
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("Marks = "+marks);
}
}
class SingleInheritance
{
public static void main(String ar[])
{
Marks obj=new Marks();
obj.getNo(546);
obj.putNo();
obj.getMarks(66);
obj.putMarks();
}
}
OUTPUT
D:\TKREC\Java>java SingleInheritance
Rollno= 546
Marks= 66.0
Example2
//super class
class A
{
int a=10;
int b=20;
}
//intermediate sub class
class add extends A
{
int sum()
{
return a+b;
}
}
public class Single
{
public static void main(String args[])
{
add obj=new add();
int x;
x=obj.sum();
System.out.println(x);
}
}
OUTPUT
D:\TKREC\Java>java Single
Sum is:30
Multiple inheritance: In multiple inheritance, a single subclass extends from multiple super
classes. Java does not support multiple inheritances due to ambiguity. For example, consider
the following Java program.
Note: Java doesn't support multiple inheritance. However, we can achieve multiple
inheritance using interfaces.
Java does not support multiple inheritances due to ambiguity. For example, consider the
following Java program.
Example
class A
{
void message()
{
System.out.println("All the Best");
}
}
class B
{
void message()
{
System.out.println("Happy Birthday");
}
}
public class Demo extends A,B //considering a scenario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}
OUTPUT
D:\TKREC\Java>javac Demo.java
Demo.java:15 error :’{‘ expected
Public class demo extends A, B // considering a scenario
1 error
The above code gives error because the compiler cannot decide which message() method is
to be invoked. Due to this reason, Java does not support multiple inheritances at the class
level but can be achieved through an interface.
Multi-level inheritance: In a class hierarchy, when a class is derived from already derived
class then that inheritance is said to be multi-level inheritance
class MultilevelInheritance
{
public static void main(String ar[])
{
Sports obj=new Sports();
obj.getNo(548);
obj.putNo();
obj.getMarks(75);
obj.putMarks();
obj.getScore(100);
obj.putScore();
}
Example2
//super class
class A
{
int a=10;
int b=20;
}
//intermediate sub class
class add extends A
{
int sum()
{
return a+b;
}
}
//intermediate sub class
class sub extends add
{
int sub()
{
return a-b;
}
}
Example
class Student
{
int rollno;
void getNo(int no)
{
rollno=no;
}
void putNo()
{
System.out.println("Rollno= "+rollno);
}
}
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("Marks= "+marks);
}
}
class Sports extends Student
{
int score;
void getScore(int scr)
{
score=scr;
}
void putScore()
{
System.out.println("Score= "+score);
}
class HierarchicalInheritance
{
public static void main(String ar[])
{
Marks m=new Marks();
Sports s=new Sports();
m.getNo(548);
m.putNo();
m.getMarks(75);
m.putMarks();
s.getNo(548);
s.putNo();
s.getScore(100);
s.putScore();
}
}
OUTPUT
D:\TKREC\Java>java HierarchicalInheritance
Rollno= 548
Marks= 75.0
Rollno= 548
Score= 100
Example2
//super class
class A
{
int a=30;
int b=10;
}
//intermediate sub class
class add extends A
{
int sum()
{
return a+b;
}
}
//intermediate sub class
class sub extends A
{
int sub()
{
return a-b;
}
}
//intermediate sub class
class mul extends A
Example
//super class
class A
{
int a=20;
Example2
//parent class
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
P.Ramesh, Assistant Professor,AIML Dept, TKREC 13
OOP through Java UNIT-2
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}
OUTPUT
D:\TKREC\Java>java Daughter
I am a Daughter
Forms of inheritance
Inheritance is used in variety of ways. The following list represents general abstract
categories and is not intended to be exhaustive.
Example
class Parent
{
int i=10;
void show()
{
System.out.println("i value= "+i);
}
}
class Child extends Parent
{
// show() will be called by Child Object in main class
}
class specialization
{
public static void main(String args[])
{
Child c=new Child();
c.show();
}
}
OUTPUT
D:\Java>java specialization
i value= 10
Example
abstract class Parent
{
int i;
abstract void show(); // only specifications
}
class Child extends Parent
{
int i=20;
void show()
{
System.out.println("i value is = "+i);
}
}
class specifications
{
public static void main(String args[])
{
Child c=new Child();
c.show();
}
}
OUTPUT
D:\Java>java specifications
i value is = 20
Example
class Parent
{
int i=20;
void show()
{
System.out.println("The value of I is = "+i);
}
}
class Child extends Parent
{
int i=30;
void display() // own implementation of child class
{
Exaple
class Parent
{
int i=15;
void show()
{
System.out.println("i value is "+i);
}
}
Example
class Parent
{
int i=5;
void show()
{
System.out.println("i value = "+i);
}
void display() // new method is also implemented
{
System.out.println("This is Parent class");
}
}
class limitation
{
public static void main(String args[])
{
Child c=new Child();
c.show();
//c.display();
}
}
OUTPUT
D:\Java>java limitation
i value = 5
D:\Java>java limitation
i value = 5
This is Parent class
Benefits of inheritance
Various benefits of inheritance are
S/w Reusability: Many programmers spend much of their time in rewriting code they have
written many times before. So with inheritance code once written can be reused.
Code sharing: Code sharing occurs at two levels. At first level many users or projects can
use the same class. In the second level sharing occurs when two or more classes developed
by a single programmer as part of a project which is being inherited from a single parent
class. Here also code is written once and reused. This is possible through inheritance.
Consistency of inheritance: When two or more classes inherit from the same superclass we
are assured that the behaviour they inherit will be the same in all cases. Thus we can
guarantee that interfaces to similar objects are in fact similar.
Rapid Prototyping: When a s/w system is constructed largely out of reusable components
development can be concentrated on understanding the new and unusual portion of the
system. Thus s/w system can be generated more quickly and easily leading to a style of
programming known as ‘Rapid Prototyping’ or ‘exploratory programming’
Polymorphism and Framework: Generally s/w is written from the bottom up, although it
may be designed from top-down. This is like building a wall where every brick must be laid
on top of another brick i.e., the lower level routines are written and on top of these slightly
higher abstraction are produced and at last more abstract elements are generated.
Polymorphism permits the programmer to generate high level reusable components.
Information Hiding: A Programmer who reuses a software need only to understand the
nature of the component and its interface. There is no need to have detailed information of
the component and it is information hiding.
Costs of inheritance
Although they are benefits with object oriented programming we must also
consider the cost of inheritance.
Execution Speed: The inherited methods which must deal with orbitary sub-
classes are often slower than specialized code. Here efficiency is often misplaced.
It is far better to develop a working system and monitor it.
Program Size: The use of any s/w library imposes a size penalty not imposed by
systems constructed for a specific project. Although the expense may be
substantial and size of program becomes less important.
The members declared as public can be accessed any where, any class and
any package.
The members declared as private can be accessed only by the methods of
same class where the private members are declared.
The members declared as protected cannot be accessed in non-subclasses
of different packages in rest of the cases they can be accessed. If you want
any member to be accessed in the subclasses of other packages they can be
declared as protected. These members are being protected from the access
facility of non-subclasses of other packages.
The members declared by nothing, like of no modifier is being placed
before a member of a class then, these members can be access only up to
package. This occurs by default. Different packages are not allowed to
access these no modifier members.
Example
/* In a class hierarchy, private members remain private to their class. This
program contains an error and will not compile. */
// Create a superclass.
class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
}
class MemberAccess
{
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
OUTPUT
D:\TKREC\Java>javac MemberAccess.java
MemberAccess.java:20: error: j has private access in A
total = i + j; // ERROR, j is not accessible here
^
1 error
This program will not compile because the reference to j inside the sum( )
method of B causes an access violation. Since j is declared as private, it is only
accessible by other members of its own class. Subclasses have no access to it
Note: A class member that has been declared as private will remain private to
its class. It is not accessible by any code outside its class, including subclasses
A more practical example that will help illustrate the power of inheritance.
Here, the final version of the Box class developed in the preceding chapter will
be extended to include a fourth component called weight. Thus, the new class
will contain a box’s width, height, depth, and weight.
Example
// This program uses inheritance to extend Box.
class Box
{
double width;
double height;
double depth;
class DemoBoxWeight
{
public static void main(String args[])
{
BoxWeight box1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight box2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol =box1.volume();
System.out.println("Volume of box1 is " + vol);
System.out.println("Weight of box1 is " + box1.weight);
System.out.println();
vol = box2.volume();
System.out.println("Volume of box2 is " + vol);
System.out.println("Weight of box2 is " + box2.weight);
}
}
OUTPUT
D:\TKREC\Java>java DemoBoxWeight
Volume of box1 is 3000.0
Weight of box1 is 34.3
BoxWeight inherits all of the characteristics of Box and adds to them the weight
component. It is not necessary for BoxWeight to re-create all of the features
found in Box. It can simply extend Box to meet its own purposes.
For example, the following class inherits Box and adds a color attribute
Super Uses
In java, super is a keyword used to refer to the parent class object. The super
keyword came into existence to solve the naming conflicts in the
inheritance. When both parent class and child class have members with the
same name, then the super keyword is used to refer to the parent class version.
Note: The super keyword is used inside the child class only.
Super to refer parent class data members: When both parent class and child
class have data members with the same name, then the super keyword is used to
refer to the parent class data member from child class.
To call the parameterized constructor of the parent class, the super keyword must
be the first statement inside the child class constructor, and we must pass the
parameter values.
Example
class A
{
int a=10;
}
class B extends A
{
int b=20;
void m1()
{
System.out.println("Value of a in Parent class:" + super.a);
System.out.println("Value of b in Childt class:" + b);
}
}
public class Test
{
public static void main(String args[])
P.Ramesh, Assistant Professor,AIML Dept, TKREC 23
OOP through Java UNIT-2
{
B obj=new B();
obj.m1();
}
}
OUTPUT:
D:\TKREC\Java>java Test
Value of a in Parent class: 10
Value of b in Child class: 20
Super to refer parent class method: When both parent class and child class
havemethod with the same name, then the super keyword is used to refer to the
parent class method from child class.
Example
class A
{
// overridden method
public void display()
{
System.out.println(" This is class A Method ");
}
}
class B extends A
{
// overriding method
public void display()
{
System.out.println(" This is class B Method ");
}
Example
class A
{
A()
{
System.out.println(" Base class Constructor ");
}
}
class B extends A
{
B()
{
super();
}
}
public class Test
{
public static void main(String args[])
{
B obj=new B();
}
}
OUTPUT:
D:\TKREC\Java>java Test
Base class Constructor
To call the parameterized constructor of the parent class, the super keyword
must be the first statement inside the child class constructor, and we must pass
the parameter values.
Example
class Teacher
{
// default or no-arg constructor
Teacher()
{
System.out.println("I am a Teacher");
}
// parameterized constructor
Teacher(String name)
{
class Main
{
public static void main(String args[])
{
Student obj = new Student();
}
}
OUTPUT:
D:\TKREC\Java>java Main
The String Name is: Teacher
I am a Student
Final with variables: When a variable defined with the final keyword, it
becomes a constant, and it does not allow us to modify the value. The variable
defined with the final keyword allows only a one-time assignment, once a value
assigned to it, never allows us to change it again.
Example
class Finalvariable
{
public static void main(String args[])
{
final int a=10;
a=30;
System.out.println(" The value of a is:" + a);
}
}
OUTPUT:
D:\TKREC\Java>javac Finalvariable.java
Final with methods: When a method defined with the final keyword, it does not allow it to
override. The final method extends to the child class, but the child class cannot override or
re-define it. It must be used as it has implemented in the parent class.
Example
class A
{
public final void display()
{
System.out.println(" This is Final Method ");
}
}
class B extends A
{
public final void display()
{
System.out.println(" This is Final Method is overridden ");
}
public static void main(String args[])
{
B obj=new B();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>javac A.java
A.java:10: error: display() in B cannot override display() in A
public final void display()
^
overridden method is final
1 error
Final with class: When a class defined with final keyword, it cannot be
extended by anyother class.
Example
final class A
{
public void display()
{
System.out.println(" This is Final Method ");
}
}
// try to extend finalclass
Polymorphism
The polymorphism is the process of defining same method with different
implementation.That means creating multiple methods with different behavior.
In java, polymorphism implemented using method overloading and method
overriding.
Example
import java.util.Arrays;
public class AdHocPolymorphismExample
{
void sorting(int[] list)
{
Arrays.parallelSort(list);
System.out.println("Integers after sort: " + Arrays.toString(list) );
}
void sorting(String[] names)
{
Arrays.parallelSort(names);
System.out.println("Names after sort: " + Arrays.toString(names) );
P.Ramesh, Assistant Professor,AIML Dept, TKREC 28
OOP through Java UNIT-2
}
public static void main(String[] args)
{
AdHocPolymorphismExample obj = new AdHocPolymorphismExample();
int list[] = {2, 3, 1, 5, 4};
obj.sorting(list); // Calling with integer array
String[] names = {"rama", "raja", "shyam", "seeta"};
obj.sorting(names); // Calling with String array
}
}
OUTPUT:
D:\TKREC\Java\UNIT-I>java AdHocPolymorphism
Integers after sort: [1, 2, 3, 4, 5]
Names after sort: [raja, rama, seeta, shyam]
Pure polymorphism: The pure polymorphism is a technique used to define the same
method with the same arguments but different implementations. In a java programming
language, pure polymorphism carried out with a method overriding concept.
In pure polymorphism, the method binding happens at run time. Pure polymorphism is also
known as run-time polymorphism. Every function call binding with the respective
overridden method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent
class function is said to be overridden.
Example
class ParentClass
{
int num = 10;
void showData()
{
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}
}
class ChildClass extends ParentClass
{
void showData()
{
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}
The method overriding enables the child class to change the implementation of the method
which acquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The method
binding which happens at run time is known as late binding. So, the method overriding
follows late binding.
Example
class A
{
public void displayInfo()
{
System.out.println(" This is class A method ");
}
}
class B extends A
{
@Override
public void displayInfo()
{
System.out.println("This is class B method ");
}
}
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 a 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.
OUTPUT:
D:\TKREC\Java>java Override
k: 3
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. For example,
consider this modified version of the preceding example:
Example
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
// overload show()
void show(String msg)
{
System.out.println(msg + k);
}
}
class Override2
{
A more practical example that uses method overriding. The following program
creates a superclass called Figure that stores the dimensions of a two-
dimensional object. It also defines a method called area( ) that computes the
area of an object. The program derives two subclasses from Figure. The first is
Rectangle and the second is Triangle. Each of these subclasses overrides area( )
so that it returns the area of a rectangle and a triangle, respectively.
Example
class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
double area()
{
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}
// override area for rectangle
double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
Figure fg;
fg = r;
System.out.println("Area is " + fg.area());
fg = t;
System.out.println("Area is " + fg.area());
fg = f;
System.out.println("Area is " + fg.area());
}
}
OUTPUT:
D:\TKREC\Java>java FindAreas
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Area for Figure is undefined.
Area is 0.0
Example
// Dynamic Method Dispatch
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
P.Ramesh, Assistant Professor,AIML Dept, TKREC 35
OOP through Java UNIT-2
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
OUTPUT:
D:\TKREC\Java>java Dispatch
Inside A's callme method
Inside B's callme method
Inside C's callme method
Syntax
abstract class <ClassName>
{
}
Example
// A Simple demonstration of abstract.
abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
P.Ramesh, Assistant Professor,AIML Dept, TKREC 36
OOP through Java UNIT-2
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}
OUTPUT:
D:\TKREC\Java>java AbstractDemo
B's implementation of callme.
This is a concrete method.
Example
abstract class Shape
{
// method of abstract class
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println(" Drawing Rectangle ");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println(" Drawing Circle ");
}
}
public class Main
{
public static void main(String[] args)
{
// create an object of Shape
Shape obj = new Circle();
obj.draw();
}
}
OUTPUT:
D:\TKREC\Java>java Main
Drawing Circle
The Object class is useful when you want to refer to any object whose type you
don't know. Because it is the super class of all other classes in java, it can refer
to any type of object.
There is one special class, Object, defined by Java. All other classes are
subclasses of Object. That is, Object is a superclass of all other classes. This
means that a reference variable of type Object can refer to an object of any other
class. Also, since arrays are implemented as classes, a variable of type Object can
also refer to any array.
Object defines the following methods, which means that they are available in
every object.
Example
class Lamp
{
// stores the value for light
// true if light is on
Example
class Lamp
{
// stores the value for light, true if light is on, false if light is off
boolean isOn;
OUTPUT:
D:\TKREC\Java>java Lamp
Light on? true
Return
Method Description Value
hashCode() returns the hashcode number for object being used. int
wait(long,int) causes the current thread to wait for the specified void
milliseconds and nanoseconds, until another thread
notifies.
Built-in Packages
User-defined Packages
Built-in Packages: The built-in packages are the packages from java API. The
Java API is a library of pre-defined classes, interfaces, and sub-packages. The
built-in packages were included in the JDK.
There are many built-in packages in java, few of them are as java, lang, io,
util, awt, javax, swing, net, sql, etc. We need to import the built-in packages to
use them in our program. To import a package, we use the import statement.
Syntax
package packageName;
The package statement must be the first statement in the program.The package
name must be a single word. The package name must use Camel case notation.
// The -d is represents destination and the. (dot operator) represents the current folder.
Example
package myPackage;
public class DefiningPackage
{
public static void main(String[] args)
{
System.out.println("This class belongs to myPackage.");
P.Ramesh, Assistant Professor,AIML Dept, TKREC 42
OOP through Java UNIT-2
}
}
OUTPUT:
D:\TKREC\Java>javac -d . DefiningPackage.java
D:\TKREC\Java>java myPackage.DefiningPackage
This class belongs to myPackage.
Now, save the above code in a file DefiningPackage.java, and compile it using
thefollowing command.
javac -d . DefiningPackage.java
The above command creates a directory with the package name myPackage,
and the DefiningPackage.class is saved into it. Run the program use the
following command.
java myPackage.DefiningPackage
When we use IDE like Eclipse, Netbeans, etc. the package structure is created
automatically.
Accessing a Packages:
Access Specifier: Specifies the scope of the data members, class and methods.
Private members of the class are available with in the class only. The
scope of private members of the class is “CLASS SCOPE”.
Public members of the class are available anywhere. The scope of public
members of the class is "GLOBAL SCOPE".
Default members of the class are available with in the class, outside the
class and in its sub class of same package. It is not available outside the
package. So the scope of default members of the class is "PACKAGE
SCOPE".
Protected members of the class are available with in the class, outside the
class and in its sub class of same package and also available to subclasses
in different package also.
The following table provides information about the visibility of both data
members and methods.
Understanding CLASSPATH
If we want to save or keep java source files and class files in different directories
or drives then we need to set the classpath to run or execute those class files
For Example
C:\classes and D:\TKREC\Java now I want to put the class file of
Sample.java Source file in the folder of C: drive
Example
public class Sample
{
public static void main(String args[])
{
System.out.println(" This is Example of setting CLASSPATH ");
}
}
OUTPUT:
To Compile
D:\TKREC\Java>javac -d C:\classes Sample.java
To Run
To run this program for D:\TKREC\Java you need to set classpath of the Directory where the
class file resides
D:\TKREC\Java>set classpath=C:\classes;.;
D:\TKREC\Java>java Sample
This is Example of setting CLASSPATH
The import statement must be after the package statement, and before any
other statement. Using an import statement, we may import a specific class
or all the classes from apackage.
Using one import statement, we may import only one package or a class. Using
an import statement, we cannot import a class directly, but it must be a part
Since the package creates a new namespace there won’t be any name conflicts
with names in other packages. Using packages it is easier to provide access
control and it is also locate the related classes.
Now save the file Add.java and create new folder for mypack (like D:\TKREC\Java\mypack)
then keep the Add.java source file in mypack folder. Now take the another class to access
this Add() method
Now we need to compile Add.java file then compile and run Demo.java file
OUTPUT:
D:\TKREC\Java>cd mypack
D:\TKREC\Java\mypack>javac Add.java
D:\TKREC\Java\mypack>cd..
D:\TKREC\Java>javac Demo.java
D:\TKREC\Java>java Demo
Addition of two Numbers: 30
Humans.java file
package animals;
class Animals
{
public void display()
{
System.out.println("All the animals are in the World");
}
}
public class Humans extends Animals
{
public void show()
{
System.out.println(" class A animals are Humans");
}
public void msg()
{
System.out.println(" Humans are Animals with Intelligence");
}
}
D:\Java>javac -d . World.java
D:\Java>java pack.World
All the animals are in the World
class A animals are Humans
Humans are Animals with Intelligence
int number=42;
String binary=Integer.toBinaryString(number);
System.out.println("Binary: " + binary);
}
}
OUTPUT:
D:\Java>java PredefinedPackages
Area: 78.53981633974483
Length: 13
Binary: 101010
In the above example, we import java.lang.* to have access to some of the fundamental
classes provided by Java, such as Math, String, and Integer. The code demonstrates the
usage of these classes by calculating the area of a circle, determining the length of a string,
and converting an integer to its binary representation.
The import statement imports only classes of the package, but not sub-packages
and its classes. We may also import sub-packages by using a symbol '.' (dot) to
separate parent package and sub-package.
Note: If you import a package, sub-packages will not be imported. i.e if you
import a package , all the classes and interfaces of that package will be imported
excluding the classes and interfaces of sub packages. Hence you need to import
the sub packages as well.
Rule: There can be only one public class in java source file and it must be
saved by the public class name.
Sub-package
Package inside the package is called sub package. It should be created to categorize the
package further.
Example
package pack.subpack;
class SubpackDemo
{
An interface in Java is one of the reference types defined in Java. It is syntactically similar to
a class but it contains abstract methods. To create an interface the keyword interface is
used. Along with abstract methods, an interface can also include constants, static methods,
nested interfaces and default methods. Any number of classes can implement an interface by
using the implements keyword. An interface an also inherit other interfaces using the extend
keyword.
Class Interface
A class can be instantiated An interface can never be instantiated
The class keyword is used to declare it The interface keyword is used
The members of a class can be declared The members of an interface are always
as private, public or protected declared as public
Contains the concrete methods i.e Contains abstract method i.e methods
methods with body without the body
The extends keyword is used to inherit The implements keyword is used to use
a class Can contain final and static an interface Cannot contain final or static
methods methods
A Java class can have constructors An interface cannot have constructors
A class can extend only one class but An interface can extend any number of
can implement any number of interfaces but cannot implement any
interfaces interface
Syntax:
interface InterfaceName
{
members declaration;
}
Example
interface HumanInterfaceExample
{
void learn(String str);
void work();
int duration = 10;
}
Converted code
interface HumanInterfaceExample
{
public abstract void learn(String str);
public abstract void work();
public static final int duration = 10;
}
P.Ramesh, Assistant Professor,AIML Dept, TKREC 50
OOP through Java UNIT-2
Syntax
class className implements InterfaceName
{
boby-of-the-class
}
/* you can access the default methods of an interface using the objects of the
implementing classes.*/
interface MyInterface
{
public static int num = 100;
public default void display()
{
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface
{
public static void main(String args[])
{
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
OUTPUT:
D:\TKREC\Java>java InterfaceExample
display method of MyInterface
Example
interface Human
{
void learn(String str);
void work();
int duration = 10;
}
In the above code defines an interface Human that contains two abstract
methods learn(), work() and one constant duration. The class Programmer
implements the interface. As it implementing the Human interface it must provide
the body of all the methods those defined in the Human interface.
Syntax:
class className implements InterfaceName1, InterfaceName2
{
boby-of-the-class
}
Example
interface Human
{
void learn(String str);
void work();
}
interface Recruitment
{
boolean screening(int score);
In the above code defines two interfaces Human and Recruitment, and a
class Programmer implements both the interfaces.
In java, an interface may be defined inside another interface, and also inside a
class. The interface that defined inside another interface or a class is known
as nested interface.The nested interface is also referred as inner interface.
The nested interface declared within an interface is public by default.
The nested interface declared within a class can be with any access
modifier.
Every nested interface is static by default.
The nested interface cannot be accessed directly. We can only access the nested
interface by using outer interface or outer class name followed by dot( . ), followed
by the nested interface name.
Example
interface OuterInterface
{
void outerMethod();
interface InnerInterface
{
void innerMethod();
}
}
Example
class OuterClass
{
interface InnerInterface
{
void innerMethod();
}
}
Example
interface SampleInterface
{
int UPPER_LIMIT = 100;
//int LOWER_LIMIT; // Error - must be initialised
}
Example
interface ParentInterface
{
void parentMethod();
}
Exploring java.io
In java, the IO operations are performed using the concept of streams.
Generally, a stream means a continuous flow of data. In java, a stream is a
logical container of datathat allows us to read from and write to it. A stream
can be linked to a data source, or data destination like a console, file or
network connection by java IO system. The stream- based IO operations are
faster than normal IO operations. The Stream is defined in the java.io package.
In Java, every program creates 3 streams automatically, and these streams are
attachedto the console.
System.out: standard output stream for console output operations.
System.in: standard input stream for console input operations.
System.err: standard error stream for console error output operations.
The Java streams support many different kinds of data, including simple bytes,
primitive data types, localized characters, and objects. Java provides two types of
streams, and they are as follows. The following picture shows how streams are
categorized, and various built-in classes used by the java IO system.
Byte Stream
Character Stream
Both character and byte streams essentially provide a convenient and
efficient way tohandle data streams in Java.
The following picture shows the classes used for byte stream operations.
InputStream class: The InputStream class has defined as an abstract class, and
it hasthe following methods which have implemented by its concrete classes.
2 int read()
It reads the next byte from the input stream.
3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in
its bytearray, b.
4 void close()
It closes the input stream and also frees any resources connected
with thisinput stream.
1 void write(int n)
It writes byte(contained in an int) to the output stream.
2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written
out.
4 void close()
It closes the output stream and also frees any resources connected
with thisoutput stream.
/* The readLine(String fmt, Object args) method is a static method of Java Console class.
It is used to provide a formatted prompt, then reads a single line of text from the console.
Syntax: -
import java.io.Console;
class ReadLineMethod
{
public static void main(String args[])
{
String str;
import java.io.*;
public class ByteStreamReadingDemoFile
{
public static void main(String[] args) throws IOException
{
FileInputStream f = new FileInputStream(new File("D:\\TKREC\\Java\\datafile.txt"));
BufferedInputStream obj = new BufferedInputStream(f);
char c = (char)obj.read();
System.out.println("Data read from a file - '" + c + "'");
}
}
We can use the BufferedOutputStream class to write data into the console, file,
socket. The BufferedOutputStream class use a method write( ) to write data.
Let's look at an example code to illustrate writing data into a file using
BufferedOutputStream.
import java.io.*;
public class WritingDemoFile
{
public static void main(String[] args) throws IOException
{
String data = "Welcome To TKR College";
BufferedOutputStream out = null;
try {
FileOutputStream fos = new FileOutputStream(new File("C:\\Java\\outputfile.txt"));
out = new BufferedOutputStream(fos);
out.write(data.getBytes());
System.out.println("Writing data into a file is success!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
OUTPUT:
D:\TKREC\Java>java WritingDemoFile
Writing data into a file is success!
In java, the character stream is a 16 bits carrier. The character stream in java
allows usto transmit 16 bits of data. The character stream was introduced in
Java 1.1 version.
The java character stream is defined by two abstract classes, Reader and Writer.
The Reader class used for character stream-based input operations.
The Writer class used for character stream-based output operations.
The Reader and Writer classes have several concrete classes to perform
various IO operations based on the character stream.
The following picture shows the classes used for character stream operations.
Reader class: The Reader class has defined as an abstract class, and it has the
following methods which have implemented by its concrete classes.
7 void close(): It closes the input stream and also frees any resources
connectedwith this input stream.
Writer class: The Writer class has defined as an abstract class, and it has the
followingmethods which have implemented by its concrete classes.
1 void flush(): It flushes the output steam by forcing out buffered bytes to
bewritten out.
6 void write(String str, int off, int len): It writes a portion of a string.
OUTPUT:
C:\Java>javac CharReadingDemoConsole.java
C:\Java>java CharReadingDemoConsole
Please enter your name: siri
Hello, siri!
import java.io.*;
public class CharReadingDemoFile
{
public static void main(String[] args) throws IOException
{
Reader in = new FileReader("C:\\Java\\datafile1.txt");
try {
char c = (char)in.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
in.close();
}
}
}
OUTPUT:
C:\Java>javac CharReadingDemoFile.java
C:\Java>java CharReadingDemoFile
Data read from a file - 'H'
import java.io.*;
public class CharWritingDemoFile
{
public static void main(String[] args) throws IOException
{
Writer out = new FileWriter("C:\\Java\\datafile2.txt");
String msg = "Welcome Students";
try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
OUTPUT:
C:\Java>javac CharWritingDemoFile.java
C:\Java>java CharWritingDemoFile
Writing done!!!