SlideShare a Scribd company logo
1 of 72
Download to read offline
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 1
DEPARTMENT OF INFORMATION TECHNOLOGY
R2017 - SEMESTER III
CS3391 – OBJECT ORIENTED PROGRAMMING
UNIT II - INHERITANCE, PACKAGES
AND INTERFACES
CLASS NOTES
Complimented with
PERSONALIZED LEARNING MATERIAL (PLM)
With
PERSONALIZED ASSESSMENT TESTS (PATs)
PERSONALIZED LEARNING MATERIAL (PLM)
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 2
An Introduction to PLM
The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of Learning Material
designed and developed by Er. K.Khaja Mohideen , Assistant Professor , Aalim Muhammed
Salegh College of Engineering, Avadi-IAF, Chennai – 600 055, India.
This material called PLM is an innovative Learning Type based Artificial Intelligence
based Suggestive learning Strategy (SLS) that recommends the selective Topics to Learners
of different Learning mind sets groups.
We identified three major such Learner Groups from Subject Learning Student
Communities and are as follows:
1) Smart Learning Groups
2) Effective Learning Groups
3) Slow Learning Groups
The three Coloring depicts the following levels of Experiencing Learners groups:
1) Smart Learning Groups – Greenish Shadow
2) Effective Learning Groups – Orange Shadow
3) Slow Learning Groups – Red Shadow
The following picture illustrates the same:
Note: The decision on PLM Topic grouping type is based on the Designer’s Academic
Experience and his Academic Excellence on the selective Course Domain.
MOST IMPORTANT IMPORTANT NOT IMPORTANT
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 3
PERSONALIZED ASSESSMENT TESTS (PATs)
An Introduction to PAT
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 4
INDEX
UNIT II - INHERITANCE, PACKAGES AND
INTERFACES
SL NO TOPIC
UNIT – I : Syllabus with PL
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
.–––.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 5
UNIT – II : Syllabus with PL
SYLLABUS:
UNIT II INHERITANCE, PACKAGES AND INTERFACES 9
Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and
Inner Classes.
Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding –
Dynamic Method Dispatch –Abstract Classes – final with Inheritance.
Packages and Interfaces: Packages – Packages and Member Access –Importing
Packages – Interfaces.
TOTAL TOPICS: 15
NOTE:
 Important Topic
 Less Important
  Not Important
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 6
1. OVERLOADING METHODS
1.1 Introduction to Overloading
 Object-Oriented Programming (OOP) is a programming language
model organizedaround objects rather than actions and data.
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.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
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);
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 7
// 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
2.1 Introduction to Parameters
 Object-oriented programming (OOP) is a programming paradigm based upon objects
(having both data and methods) that aims to incorporate the advantages of modularity
and reusability.
The Object Class
 There is one special class, Object, defined by Java.
 All other classes are subclasses of Object.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 8
 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.
 The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may
override the others.
 However, notice two methods now: equals( ) and toString( ).
 The equals( ) method compares two objects. It returns true if the objects are equal, and false
otherwise.
 The precise definition of equality can vary, depending on the type of objects being compared.
 The toString( ) method returns a string that contains a description of the object on which it is
called.
 Also, this method is automatically called when an object is output using println( ). Many
classes override this method.
 Doing so allows them to tailor a description specifically for the types of objects that they
create.
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 iscalled 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;
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 9
}
// 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.
That is, theversion of show( ) inside B overrides the version declared in A.
If you wish to access the superclass version of an overridden method, you can do so by using
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 10
super.
For example, in this version of B, the superclass version of show( ) is invoked within the
subclass’ version.
This allows all instance variables to be displayed.
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 11
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; }
// Method returns an object
ObjectReturnDemo incrByTen()
{
ObjectReturnDemo temp
= new ObjectReturnDemo(a + 10);
return temp;
}
}
// Class 2
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating object of class1 inside main() method
ObjectReturnDemo ob1 = new ObjectReturnDemo(2);
ObjectReturnDemo ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
}
}
Output
ob1.a: 2
ob2.a: 12
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 12
4. STATIC, NESTED INNER CLASSES
4.1 c STATIC MEMBERS
Static is a non-access modifier in Java which is applicable for the following:
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.
Important points for static variables :-
 We can create static variables at class-level only.
 static block and static variables are executed in order they are present in a program.
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:
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 13
 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.
4.2 Static Classes
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);
}
}
4.3 Nested Classes
Nested Classes
The Java programming language allows you define a class within another class. Such a class is called
a nested class and is illustrated here:
class EnclosingClass {
...
class ANestedClass {
...
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 14
}
 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.
As a member of its enclosing class, a nested class has a special privilege:
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).
A static nested class is called just that: a static nested class.
A nonstatic nested class is called an inner class.
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 15
 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.
Consider the following 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.
An InnerClass Exists Within an Instance of EnclosingClass
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 16
You may encounter all of these nested classes in the Java platform API and be required to use them.
Summary of Nested Classes
A class defined within another class is called a nested class. Like other members of a class, a nested
class can be declared static or not. A nonstatic nested class is called an inner class. An instance of an
inner class can exist only within an instance of its enclosing class and has access to its enclosing
class's members even if they are declared private.
The following table shows the types of nested classes:
Types of Nested Classes
Type Scope Inner
static nested class member no
inner [non-static] class member yes
local class local yes
anonymous class only the point where it is defined yes
4.3 Inner Classes
4.3.1 Inner Classes
An inner class is a class that is defined inside another class.
Why inner classes?
There are four reasons:
• An object of an inner class can access the implementation of the object that created it—including
data that would otherwise be private.
• Inner classes can be hidden from other classes in the same package.
• Anonymous inner classes are handy when you want to define callbacks on the fly.
INNER CLASSES
Inner class means one class which is a member of another class.
There are basically four types of inner classes in java.
1) Nested Inner class
2) Method Local inner classes
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 17
3) Anonymous inner classes
4) Static nested classes
Nested Inner class
Nested Inner class can access any private instance variable of outer class. Like any other instance
variable, we can have access modifier private, protected, public and default modifier. Like class,
interface can also be nested and can have access specifiers.
Example:
class Outer {
// Simple nested inner class class Inner {
CS8392 /Object Oriented Programming
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) { Outer.Inner in = new Outer().new Inner(); in.show();
}
}
Output:
In a nested class method
Method Local inner classes
Inner class can be declared within a method of an outer class. In the following example, Inner is an
inner class in outerMethod().
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");
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 18
}
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
Static nested classes
Static nested classes are not technically an inner class. They are like a static member of outer lass.
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
Anonymous inner classes
Anonymous inner classes are declared without any name at all. They are created in two ways. a) As
subclass of specified type
class Demo { void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
// An anonymous class with Demo as base class static Demo d = new Demo() {
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 19
void show() { super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){ d.show();
}
}
Output:
i am in show method of super class i am in Flavor1Demo class
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().
In anonymous class show() method is overridden.
b) As implementer of the specified interface
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 20
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.
Uses of inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Syntax:
class subClass extends superClass
{
//methods and fields
}
Terms used in Inheritence
 Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in previous
class.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 21
Types of Inheritance
Types of inheritance in java are
a) Single inheritance
b) Multilevel inheritance
c) Hierarchical inheritance.
d) Multiple inheritance
e) Hybridinheritance
Note: Multiple and hybridinheritance is supported through interface only.
6. TYPES OF INHERITANCE
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 22
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:
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 23
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 ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC
reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 24
Output :
disp() method of ClassA
disp() method of ClassB
disp() method of ClassC
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");
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 25
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();
//Assigning ClassD object to ClassD reference
ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 26
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
Usage of super keyword
1. super() invokes the constructor of the parent class.
2. super.variable_name refers to the variable in the parent class.
3. super.method_name refers to the method of the parent class.
1. super() invokes the constructor of the parent class
 super() will invoke the constructor of the parent class.
 Even when you don’t add super() keyword the compiler will add one and will invoke the
Parent Class constructor.
Example:
class ParentClass
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 27
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");
}
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 28
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
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 29
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();
//Calling parameterized constructor
SubClass s1 = new SubClass(10);
}
}
Output
Parent Class default Constructor called
Child Class default Constructor called
Parent Class parameterized Constructor, value: 10
Child Class parameterized Constructor, value: 10
2. super.variable_name refers to the variable in the parent class
When we have the same variable in both parent and subclass
class ParentClass
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 30
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;
void disp()
{
System.out.println("Value is : "+val);
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.disp();
}
}
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);
}
public static void main(String args[])
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 31
{
SubClass s = new SubClass(); s.disp();
}
}
Output
Value is : 999
1. super.method_nae refers to the method of the parent class
When you override the Parent Class method in the Child Class without super keywords support you
will not be able to call the Parent Class method. Let’s look into the below example
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()
{
disp();
}
public static void main(String args[])
{
}
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 32
Output:
SubClass s = new SubClass(); s.show();
Child Class method
 Here we have overridden the Parent Class disp() method in the SubClass and hence SubClass
disp() method is called.
 If we want to call the Parent Class disp() method also means then we have to use the super
keyword for it.
class ParentClass
{
void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
CS8392 /Object Oriented Programming
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();
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 33
}
Output
Child Class method Parent Class method
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 34
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. .
Method Overriding Example
 Lets take a simple example to understand this. We have two classes: A child class Boy and a
parent class Human.
 The Boy class extends Human class. Both the classes have a common method void eat(). Boy
class is giving its own implementation to the eat() method or in other words it is overriding
the eat() method.
 The purpose of Method Overriding is clear here.
 Child class wants to give its own implementation so that when it calls this method, it prints
Boy is eating instead of Human is eating.
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();
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 35
}
}
Output:
Boy is eating
Advantage of method overriding
The main advantage of method overriding is that the class can give its own specific implementation
to a inherited method without even modifying the parent class code.
This is helpful when a class has several child classes, so if a child class needs to use the parent class
method, it can use it and the other classes that want to have different implementation can use
overriding feature to make changes without touching the parent class code.
9. DYNAMIC METHOD DISPATCH
Dynamic Method Dispatch
 Method Overriding is an example of runtime polymorphism.
 When a parent class reference points to the child class object then the call to the overridden
method is determined at runtime, because during method call which method(parent class or
child class) is to be executed is determined by the type of object.
 This process in which call to the overridden method is resolved at runtime is known as
dynamic method dispatch.
Lets see an example to understand this:
class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 36
System.out.println("new method of child class");
}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj = new ABC();
obj.disp();
/* When parent class reference refers to the child class object
* then the overriding method (method of child class) is called.
* This is called dynamic method dispatch and runtime polymorphism
*/
ABC obj2 = new Demo();
obj2.disp();
}
}
Output:
disp() method of parent class
disp() method of Child class
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
Rules of method overriding in Java
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 37
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();
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 38
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.
Binding of overridden methods happen at runtime which is known as dynamic binding.
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.
Super keyword in Method Overriding
The super keyword is used for calling the parent class method/constructor. super.myMethod() calls
the myMethod() method of base class while super() calls the constructor of base class. Let’s see the
use of super in method Overriding.
As we know that we we override a method in child class, then call to the method using child class
object calls the overridden method. By using super we can call the overridden method as shown in
the example below:
class ABC{
public void myMethod()
{
System.out.println("Overridden method");
}
}
class Demo extends ABC{
public void myMethod(){
//This will call the myMethod() of parent class
super.myMethod();
System.out.println("Overriding method");
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 39
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod();
}
}
Output:
Class ABC: mymethod()
Class Test: mymethod()
***************************
10. ABSTRACT CLASSES
ABSTRACT CLASSES
 A class that is declared with abstract keyword, is known as abstract class in java.
 It can have abstract and non-abstract methods (method with body).
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
 Abstraction lets you focus on what the object does instead of how it does it.
 It needs to be extended and its method implemented. It cannot be instantiated.
Example abstract class:
abstract class A{}
abstract method:
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract void printStatus();//no body and abstract
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 40
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");
}
}
//In real scenario, method is called by programmer or user
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
 Abstract class having constructor, data member, methods
 An abstract class can have data member, abstract method, method body, constructor and
even main() method.
Example2:
File: TestAbstraction2.java
//example of abstract class that have method body
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 41
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 42
{
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
Use of All Features of Abstract Class
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. Such a class determines
the nature of the methods that the subclasses must implement.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 43
Here is the source code of the Java Program to Illustrate Use of All Features of Abstract Class. The
Java program is successfully compiled and run on a Windows system.
Example1:
abstract class Operations
{
float a = 12, b = 6, c;
abstract void add();
void subtract()
{
c = a - b;
System.out.println("Result:"+c);
}
abstract void multiply();
void divide()
{
c = a / b;
System.out.println("Result:"+c);
}
}
public class Abstract_Demo extends Operations
{
@Override
void add()
{
c = a + b;
System.out.println("Result:"+c);
}
@Override
void multiply()
{
c = a * b;
System.out.println("Result:"+c);
}
public static void main(String[] args)
{
Abstract_Demo obj = new Abstract_Demo();
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 44
obj.add();
obj.subtract();
obj.multiply();
obj.divide();
}
}
Output:
$ javac Abstract_Demo.java
$ java Abstract_Demo
Result:18.0
Result:6.0
Result:72.0
Result:2.0
Example 2:
abstract class Calculation
{
float a = 12, b = 6, c;
abstract void add();
void subtract()
{
c = a - b;
System.out.println("Result:"+c);
}
abstract void multiply();
void divide()
{
c = a / b;
System.out.println("Result:"+c);
}
}
public class AbstractionDemo extends Calculation
{
void add()
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 45
c = a + b;
System.out.println("Result:"+c);
}
void multiply()
{
c = a * b;
System.out.println("Result:"+c);
}
public static void main(String[] args)
{
AbstractionDemo obj = new AbstractionDemo;
obj.add();
obj.subtract();
obj.multiply();
obj.divide();
}
}
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
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 46
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 47
{
void method2()
{
System.out.println("World");
}
public static void main(String s[])
{
C c=new C();
c.method1();
c.method2();
}
}
***************
11. FINAL WITH INHERITANCE
Using final with inheritance
 During inheritance, we must declare methods with the final keyword for which we are
required to follow the same implementation throughout all the derived classes.
 Note that it is not necessary to declare final methods in the initial stage of inheritance(base
class always).
 We can declare a final method in any subclass for which we want that if any other class
extends this subclass, then it must follow the same implementation of the method as in that
subclass.
// Java program to illustrate
// use of final with inheritance
// base class
abstract class Shape
{
private double width;
private double height;
// Shape class parameterized constructor
public Shape(double width, double height)
{
this.width = width;
this.height = height;
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 48
// getWidth method is declared as final
// so any class extending
// Shape can't override it
public final double getWidth()
{
return width;
}
// getHeight method is declared as final
// so any class extending Shape
// can not override it
public final double getHeight()
{
return height;
}
// method getArea() declared abstract because
// it upon its subclasses to provide
// complete implementation
abstract double getArea();
}
// derived class one
class Rectangle extends Shape
{
// Rectangle class parameterized constructor
public Rectangle(double width, double height)
{
// calling Shape class constructor
super(width, height);
}
// getArea method is overridden and declared
// as final so any class extending
// Rectangle can't override it
@Override
final double getArea()
{
return this.getHeight() * this.getWidth();
}
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 49
//derived class two
class Square extends Shape
{
// Square class parameterized constructor
public Square(double side)
{
// calling Shape class constructor
super(side, side);
}
// getArea method is overridden and declared as
// final so any class extending
// Square can't override it
@Override
final double getArea()
{
return this.getHeight() * this.getWidth();
}
}
// Driver class
public class Test
{
public static void main(String[] args)
{
// creating Rectangle object
Shape s1 = new Rectangle(10, 20);
// creating Square object
Shape s2 = new Square(10);
// getting width and height of s1
System.out.println("width of s1 : "+ s1.getWidth());
System.out.println("height of s1 : "+ s1.getHeight());
// getting width and height of s2
System.out.println("width of s2 : "+ s2.getWidth());
System.out.println("height of s2 : "+ s2.getHeight());
//getting area of s1
System.out.println("area of s1 : "+ s1.getArea());
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 50
//getting area of s2
System.out.println("area of s2 : "+ s2.getArea());
}
}
12. PACKAGES AND INTERFACES: PACKAGES
1) Introduction to Packages
What is Package in Java?
A Package is a collection of related classes.
It helps organize your classes into a folder structure and make it easy to locate and use them.
More importantly, it helps improve re-usability.
 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.
Creating and Using Packages
To make types easier to find and use, to avoid naming conflicts, and to control access, programmers
bundle groups of related types into packages.
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 51
 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
There are two types of packages in java. They are:
a) Standard Packages
b) User Defined 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:
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 52
 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.
//in the Graphic.java file
public abstract class Graphic {
. . .
}
//in the Circle.java file
public class Circle extends Graphic implements Draggable {
. . .
}
//in the Rectangle.java file
public class Rectangle extends Graphic implements Draggable {
. . .
}
//in the Draggable.java file
public interface Draggable {
. . .
}
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.
Worthy note on packages:
 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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 53
 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:
 Refer to the member by its long (qualified) name
 Import the package member
 Import the member's entire package
2) Syntax to declare packages
How to Create PACKAGE in Java?
Syntax:-
package nameOfPackage;
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 54
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.
Step 1) Consider the following code,
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
Step 2) In next step, save this file as demo.java
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 55
Step 3) In this step, we compile the file.
The compilation is completed. A class file c1 is created. However, no package is created? Next step
has the solution
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 56
Step 4) Now we have to create a package, use the command
javac –d . demo.java
This command forces the compiler to create a package.
The "." operator represents the current working directory.
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.
Step 6) Compile the same file using the following code
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.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 57
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
Step 8) Compile the file
As seen in below screenshot, it creates a sub-package p2 having class c1 inside the package.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 58
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.
***********************
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 59
13. PACKAGES AND MEMBER ACCESS
13.1 Introduction to Packages
Creating and Using Packages
To make types easier to find and use, to avoid naming conflicts, and to control access, programmers
bundle groups of related types into packages.
Definition: A package is a collection of related types providing access protection and name space
management.
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.
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.
//in the Graphic.java file
public abstract class Graphic {
. . .
}
//in the Circle.java file
public class Circle extends Graphic implements Draggable {
. . .
}
//in the Rectangle.java file
public class Rectangle extends Graphic implements Draggable {
. . .
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 60
//in the Draggable.java file
public interface Draggable {
. . .
}
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;
public class Circle extends Graphic implements Draggable {
. . .
}
The Circle class is a public member of the graphics package.
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;
public class Rectangle extends Graphic implements Draggable {
. . .
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 61
}
Worthy note on packages:
 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.
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:
 Refer to the member by its long (qualified) name
 Import the package member
 Import the member's entire package
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 62
Each is appropriate for different situations, as explained in the sections that follow.
Referring to a Package Member by Name
 So far, the examples in this tutorial have referred to types by their simple names, such as
Rectangle.
 You can use a package member's simple name if the code you are writing is in the same
package as that member or if that member has been imported.
 However, if you are trying to use a member from a different package and that package has not
been imported, you must use the member's qualified name, which includes the package name.
Here is the qualified name for the Rectangle class declared in the graphics package in the previous
example.
graphics.Rectangle
You could use this long name to create an instance of graphics.Rectangle:
graphics.Rectangle myRect = new 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.
*************
14. IMPORTING PACKAGES
Importing a Package Member
To import a specific member into the current file, put an import statement at the beginning of the file
before any class or interface definitions but after the package statement, if there is one.
Here's how you would import the Circle class from the graphics package created in the previous
section.
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 63
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.
Importing an Entire Package
To import all the types contained in a particular package, use the import statement with the asterisk
(*) wildcard character.
import graphics.*;
Now you can refer to any class or interface in the graphics package by its short name.
Circle myCircle = new Circle();
Rectangle myRectangle = new Rectangle();
 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.
Example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 64
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package?
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
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).
How to run java package program?
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
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.
*********************
15. INTERFACES
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
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 65
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>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Relationship between classes and interfaces
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();
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 66
obj.print();
}
}
Output:
Hello
Example: interfaceDrawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw(){System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw(){System.out.println("drawing circle");}
}
class TestInterface1{
public static void main(String args[])
{
Drawable d=new Circle();//In real scenario, object is provided by method e.g.
getDrawable()d.draw();
}
}
Output:
drawing circle
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known asmultiple inheritance.
Example:
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 67
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");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 68
Hell
o
Wel
com
e
Interface inheritance
A class implements interface but one interface extends another
interface .Example:
interface
Printable{
void print();
}
interface Showable extends
Printable{void show();
}
class TestInterface4 implements
Showable{ public void
print(){System.out.println("Hello");}
public void
show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}}
Output:
Hell
o
Wel
com
e
Nested Interface in Java
An interface can have another interface i.e. known as nested
interface.interface printable{
void print();
interface
MessagePrintable{void
msg();
}
}
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 69
Key points to remember about interfaces:
1) We can’t instantiate an interface in java. That means we cannot create the object of an
interface
2) Interface provides full abstraction as none of its methods have body. On the other
hand abstract class provides partial abstraction as it can have abstract and
concrete(methods with body) methods both.
3) “implements” keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to
be mentioned as public.
5) Class that implements any interface must implement all the methods of that interface,
else theclass should be declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by
default.interface Try
{
int a=10;
publicint
a=10;
public static final
int a=10;final int
a=10;
static int a=0;
}
All of the above statements are identical.
9) Interface variables must be initialized at the time of declaration otherwise compiler
will throwan error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is not
initialized at the time of declaration.
10) Inside any implementation class, you cannot change the variables declared in
interface because by default, they are public, static and final. Here we are implementing
the interface
“Try” which has a variable x. When we tried to set the value for variable x we got
compilation error as the variable x is public static final by default and final variables can
not be re-initialized.class Sample implements Try
{
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 70
public static void main(String args[])
{
x=20; //compile time error
}
}
11) An interface can extend any interface but cannot implement it. Class implements
interfaceand interface extends interface.
12) A class can implement any number of interfaces.
13) If there are two or more same methods in two interfaces and a class
implements bothinterfaces, implementation of the method once is enough.
interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
14) A class cannot implement two interfaces that have methods with same name but
differentreturn type.
interface A
{
public void aaa();
}
interface B
{
public int aaa();
}
class Central implements A,B
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 71
{
public void aaa() // error
{
}
public int aaa() // error
{
}
public static void main(String args[])
{
}
}
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);
}
}
Advantages of interface in java:
 Without bothering about the implementation part, we can achieve the security of
implementation
 In java, multiple inheritance is not allowed, however you can use interface to make
useof it as you can implement more than one interface.
DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE
ABSTRACT CLASS INTERFACE
Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 72
1) Abstract class can have abstract and non-
abstract methods.
Interface can have only abstract methods.
Since Java 8, it can have default and static
methods also.
2) Abstract class doesn't support multiple
inheritance.
Interface supports multiple inheritance.
3) Abstract class can have final, non-final,
static and non-static variables.
Interface has only static and final variables.
4) Abstract class can provide the
implementation of interface.
Interface can't provide the implementation of
abstract class.
5) The abstract keyword is used to declare
abstract class.
The interface keyword is used to declare
interface.
6) An abstract class can extend another Java
class and implement multiple Java interfaces.
An interface can extend another Java
interface only.
7) An abstract class can be extended using
keyword extends.
An interface class can be implemented using
keyword implements
8) A Java abstract class can have class
members like private, protected, etc.
Members of a Java interface are public by
default.
9)Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
************************

More Related Content

What's hot

Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programmingElizabeth Thomas
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - RecursionAdan Hubahib
 

What's hot (20)

Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java applets
Java appletsJava applets
Java applets
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java package
Java packageJava package
Java package
 
Java IO
Java IOJava IO
Java IO
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
 

Similar to CS3391 -OOP -UNIT – II NOTES FINAL.pdf

OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ Dev Chauhan
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesSakkaravarthiS1
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingRenas Rekany
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxVeerannaKotagi1
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
U2 JAVA.pptx
U2 JAVA.pptxU2 JAVA.pptx
U2 JAVA.pptxmadan r
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxRDeepa9
 
be5b99cpl-lec11-slides.pdf
be5b99cpl-lec11-slides.pdfbe5b99cpl-lec11-slides.pdf
be5b99cpl-lec11-slides.pdfElisée Ndjabu
 

Similar to CS3391 -OOP -UNIT – II NOTES FINAL.pdf (20)

OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
17515
1751517515
17515
 
Inheritance
InheritanceInheritance
Inheritance
 
U2 JAVA.pptx
U2 JAVA.pptxU2 JAVA.pptx
U2 JAVA.pptx
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
CHAPTER 3 part1.pdf
CHAPTER 3 part1.pdfCHAPTER 3 part1.pdf
CHAPTER 3 part1.pdf
 
be5b99cpl-lec11-slides.pdf
be5b99cpl-lec11-slides.pdfbe5b99cpl-lec11-slides.pdf
be5b99cpl-lec11-slides.pdf
 
Inheritance
InheritanceInheritance
Inheritance
 

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING

More from AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING (20)

JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
INTRO TO PROGRAMMING.ppt
INTRO TO PROGRAMMING.pptINTRO TO PROGRAMMING.ppt
INTRO TO PROGRAMMING.ppt
 
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptxCS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
CS3391 OOP UT-I T4 JAVA BUZZWORDS.pptx
 
CS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T1 OVERVIEW OF OOPCS3391 OOP UT-I T1 OVERVIEW OF OOP
CS3391 OOP UT-I T1 OVERVIEW OF OOP
 
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMINGCS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
CS3391 OOP UT-I T3 FEATURES OF OBJECT ORIENTED PROGRAMMING
 
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptxCS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
CS3391 OOP UT-I T2 OBJECT ORIENTED PROGRAMMING PARADIGM.pptx
 
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdfCS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
 
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
CS3391 -OOP -UNIT – IV NOTES FINAL.pdfCS3391 -OOP -UNIT – IV NOTES FINAL.pdf
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
CS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdfCS8080 information retrieval techniques unit iii ppt in pdf
CS8080 information retrieval techniques unit iii ppt in pdf
 
CS8080 IRT UNIT I NOTES.pdf
CS8080 IRT UNIT I  NOTES.pdfCS8080 IRT UNIT I  NOTES.pdf
CS8080 IRT UNIT I NOTES.pdf
 
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdfCS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
CS8080_IRT_UNIT - III T14 SEQUENTIAL SEARCHING.pdf
 
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdfCS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
CS8080_IRT_UNIT - III T15 MULTI-DIMENSIONAL INDEXING.pdf
 
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
CS8080_IRT_UNIT - III T13 INVERTED  INDEXES.pdfCS8080_IRT_UNIT - III T13 INVERTED  INDEXES.pdf
CS8080_IRT_UNIT - III T13 INVERTED INDEXES.pdf
 
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
CS8080  IRT UNIT - III  SLIDES IN PDF.pdfCS8080  IRT UNIT - III  SLIDES IN PDF.pdf
CS8080 IRT UNIT - III SLIDES IN PDF.pdf
 
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdfCS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
 
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdfCS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
CS8080_IRT_UNIT - III T12 INDEXING AND SEARCHING.pdf
 
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdfCS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
CS8080_IRT_UNIT - III T11 ORGANIZING THE CLASSES.pdf
 
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T10  ACCURACY AND ERROR.pdfCS8080_IRT_UNIT - III T10  ACCURACY AND ERROR.pdf
CS8080_IRT_UNIT - III T10 ACCURACY AND ERROR.pdf
 
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdfCS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
CS8080_IRT_UNIT - III T9 EVALUATION METRICS.pdf
 

Recently uploaded

High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 

Recently uploaded (20)

High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 

CS3391 -OOP -UNIT – II NOTES FINAL.pdf

  • 1. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 1 DEPARTMENT OF INFORMATION TECHNOLOGY R2017 - SEMESTER III CS3391 – OBJECT ORIENTED PROGRAMMING UNIT II - INHERITANCE, PACKAGES AND INTERFACES CLASS NOTES Complimented with PERSONALIZED LEARNING MATERIAL (PLM) With PERSONALIZED ASSESSMENT TESTS (PATs) PERSONALIZED LEARNING MATERIAL (PLM)
  • 2. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 2 An Introduction to PLM The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of Learning Material designed and developed by Er. K.Khaja Mohideen , Assistant Professor , Aalim Muhammed Salegh College of Engineering, Avadi-IAF, Chennai – 600 055, India. This material called PLM is an innovative Learning Type based Artificial Intelligence based Suggestive learning Strategy (SLS) that recommends the selective Topics to Learners of different Learning mind sets groups. We identified three major such Learner Groups from Subject Learning Student Communities and are as follows: 1) Smart Learning Groups 2) Effective Learning Groups 3) Slow Learning Groups The three Coloring depicts the following levels of Experiencing Learners groups: 1) Smart Learning Groups – Greenish Shadow 2) Effective Learning Groups – Orange Shadow 3) Slow Learning Groups – Red Shadow The following picture illustrates the same: Note: The decision on PLM Topic grouping type is based on the Designer’s Academic Experience and his Academic Excellence on the selective Course Domain. MOST IMPORTANT IMPORTANT NOT IMPORTANT
  • 3. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 3 PERSONALIZED ASSESSMENT TESTS (PATs) An Introduction to PAT
  • 4. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 4 INDEX UNIT II - INHERITANCE, PACKAGES AND INTERFACES SL NO TOPIC UNIT – I : Syllabus with PL 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 .–––.
  • 5. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 5 UNIT – II : Syllabus with PL SYLLABUS: UNIT II INHERITANCE, PACKAGES AND INTERFACES 9 Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and Inner Classes. Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding – Dynamic Method Dispatch –Abstract Classes – final with Inheritance. Packages and Interfaces: Packages – Packages and Member Access –Importing Packages – Interfaces. TOTAL TOPICS: 15 NOTE:  Important Topic  Less Important   Not Important
  • 6. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 6 1. OVERLOADING METHODS 1.1 Introduction to Overloading  Object-Oriented Programming (OOP) is a programming language model organizedaround objects rather than actions and data. 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. There are two ways to overload the method in java 1. By changing number of arguments 2. By changing the data type 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); }
  • 7. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 7 // 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 2.1 Introduction to Parameters  Object-oriented programming (OOP) is a programming paradigm based upon objects (having both data and methods) that aims to incorporate the advantages of modularity and reusability. The Object Class  There is one special class, Object, defined by Java.  All other classes are subclasses of Object.
  • 8. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 8  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.  The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override the others.  However, notice two methods now: equals( ) and toString( ).  The equals( ) method compares two objects. It returns true if the objects are equal, and false otherwise.  The precise definition of equality can vary, depending on the type of objects being compared.  The toString( ) method returns a string that contains a description of the object on which it is called.  Also, this method is automatically called when an object is output using println( ). Many classes override this method.  Doing so allows them to tailor a description specifically for the types of objects that they create. 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 iscalled 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;
  • 9. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 9 } // 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. That is, theversion of show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden method, you can do so by using
  • 10. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 10 super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass’ version. This allows all instance variables to be displayed. 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.
  • 11. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 11 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; } // Method returns an object ObjectReturnDemo incrByTen() { ObjectReturnDemo temp = new ObjectReturnDemo(a + 10); return temp; } } // Class 2 // Main class public class GFG { // Main driver method public static void main(String args[]) { // Creating object of class1 inside main() method ObjectReturnDemo ob1 = new ObjectReturnDemo(2); ObjectReturnDemo ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); } } Output ob1.a: 2 ob2.a: 12
  • 12. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 12 4. STATIC, NESTED INNER CLASSES 4.1 c STATIC MEMBERS Static is a non-access modifier in Java which is applicable for the following: 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. Important points for static variables :-  We can create static variables at class-level only.  static block and static variables are executed in order they are present in a program. 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:
  • 13. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 13  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. 4.2 Static Classes 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); } } 4.3 Nested Classes Nested Classes The Java programming language allows you define a class within another class. Such a class is called a nested class and is illustrated here: class EnclosingClass { ... class ANestedClass { ... }
  • 14. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 14 }  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. As a member of its enclosing class, a nested class has a special privilege: 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). A static nested class is called just that: a static nested class. A nonstatic nested class is called an inner class. 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.
  • 15. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 15  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. Consider the following 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. An InnerClass Exists Within an Instance of EnclosingClass 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.
  • 16. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 16 You may encounter all of these nested classes in the Java platform API and be required to use them. Summary of Nested Classes A class defined within another class is called a nested class. Like other members of a class, a nested class can be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private. The following table shows the types of nested classes: Types of Nested Classes Type Scope Inner static nested class member no inner [non-static] class member yes local class local yes anonymous class only the point where it is defined yes 4.3 Inner Classes 4.3.1 Inner Classes An inner class is a class that is defined inside another class. Why inner classes? There are four reasons: • An object of an inner class can access the implementation of the object that created it—including data that would otherwise be private. • Inner classes can be hidden from other classes in the same package. • Anonymous inner classes are handy when you want to define callbacks on the fly. INNER CLASSES Inner class means one class which is a member of another class. There are basically four types of inner classes in java. 1) Nested Inner class 2) Method Local inner classes
  • 17. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 17 3) Anonymous inner classes 4) Static nested classes Nested Inner class Nested Inner class can access any private instance variable of outer class. Like any other instance variable, we can have access modifier private, protected, public and default modifier. Like class, interface can also be nested and can have access specifiers. Example: class Outer { // Simple nested inner class class Inner { CS8392 /Object Oriented Programming public void show() { System.out.println("In a nested class method"); } } } class Main { public static void main(String[] args) { Outer.Inner in = new Outer().new Inner(); in.show(); } } Output: In a nested class method Method Local inner classes Inner class can be declared within a method of an outer class. In the following example, Inner is an inner class in outerMethod(). 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"); }
  • 18. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 18 } 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 Static nested classes Static nested classes are not technically an inner class. They are like a static member of outer lass. 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 Anonymous inner classes Anonymous inner classes are declared without any name at all. They are created in two ways. a) As subclass of specified type class Demo { void show() { System.out.println("i am in show method of super class"); } } class Flavor1Demo { // An anonymous class with Demo as base class static Demo d = new Demo() {
  • 19. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 19 void show() { super.show(); System.out.println("i am in Flavor1Demo class"); } }; public static void main(String[] args){ d.show(); } } Output: i am in show method of super class i am in Flavor1Demo class 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(). In anonymous class show() method is overridden. b) As implementer of the specified interface 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.
  • 20. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 20 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. Uses of inheritance in java  For Method Overriding (so runtime polymorphism can be achieved).  For Code Reusability. Syntax: class subClass extends superClass { //methods and fields } Terms used in Inheritence  Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.  Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.  Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.  Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in previous class.
  • 21. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 21 Types of Inheritance Types of inheritance in java are a) Single inheritance b) Multilevel inheritance c) Hierarchical inheritance. d) Multiple inheritance e) Hybridinheritance Note: Multiple and hybridinheritance is supported through interface only. 6. TYPES OF INHERITANCE
  • 22. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 22 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:
  • 23. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 23 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 ClassB { public void dispC() { System.out.println("disp() method of ClassC"); } public static void main(String args[]) { //Assigning ClassC object to ClassC reference ClassC c = new ClassC(); //call dispA() method of ClassA c.dispA(); //call dispB() method of ClassB c.dispB(); //call dispC() method of ClassC c.dispC(); } }
  • 24. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 24 Output : disp() method of ClassA disp() method of ClassB disp() method of ClassC 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"); }
  • 25. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 25 } public class HierarchicalInheritanceTest { public static void main(String args[]) { //Assigning ClassB object to ClassB reference ClassB b = new ClassB(); //call dispB() method of ClassB b.dispB(); //call dispA() method of ClassA b.dispA(); //Assigning ClassC object to ClassC reference ClassC c = new ClassC(); //call dispC() method of ClassC c.dispC(); //call dispA() method of ClassA c.dispA(); //Assigning ClassD object to ClassD reference ClassD d = new ClassD(); //call dispD() method of ClassD d.dispD(); //call dispA() method of ClassA d.dispA(); } } Output : disp() method of ClassB disp() method of ClassA disp() method of ClassC disp() method of ClassA disp() method of ClassD
  • 26. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 26 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 Usage of super keyword 1. super() invokes the constructor of the parent class. 2. super.variable_name refers to the variable in the parent class. 3. super.method_name refers to the method of the parent class. 1. super() invokes the constructor of the parent class  super() will invoke the constructor of the parent class.  Even when you don’t add super() keyword the compiler will add one and will invoke the Parent Class constructor. Example: class ParentClass {
  • 27. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 27 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"); } }
  • 28. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 28 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 {
  • 29. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 29 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(); //Calling parameterized constructor SubClass s1 = new SubClass(10); } } Output Parent Class default Constructor called Child Class default Constructor called Parent Class parameterized Constructor, value: 10 Child Class parameterized Constructor, value: 10 2. super.variable_name refers to the variable in the parent class When we have the same variable in both parent and subclass class ParentClass {
  • 30. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 30 int val=999; } public class SubClass extends ParentClass { int val=123; void disp() { System.out.println("Value is : "+val); } public static void main(String args[]) { SubClass s = new SubClass(); s.disp(); } } 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); } public static void main(String args[])
  • 31. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 31 { SubClass s = new SubClass(); s.disp(); } } Output Value is : 999 1. super.method_nae refers to the method of the parent class When you override the Parent Class method in the Child Class without super keywords support you will not be able to call the Parent Class method. Let’s look into the below example 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() { disp(); } public static void main(String args[]) { } }
  • 32. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 32 Output: SubClass s = new SubClass(); s.show(); Child Class method  Here we have overridden the Parent Class disp() method in the SubClass and hence SubClass disp() method is called.  If we want to call the Parent Class disp() method also means then we have to use the super keyword for it. class ParentClass { void disp() { System.out.println("Parent Class method"); } } public class SubClass extends ParentClass { CS8392 /Object Oriented Programming 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(); }
  • 33. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 33 } Output Child Class method Parent Class method 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
  • 34. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 34 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. . Method Overriding Example  Lets take a simple example to understand this. We have two classes: A child class Boy and a parent class Human.  The Boy class extends Human class. Both the classes have a common method void eat(). Boy class is giving its own implementation to the eat() method or in other words it is overriding the eat() method.  The purpose of Method Overriding is clear here.  Child class wants to give its own implementation so that when it calls this method, it prints Boy is eating instead of Human is eating. 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();
  • 35. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 35 } } Output: Boy is eating Advantage of method overriding The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code. This is helpful when a class has several child classes, so if a child class needs to use the parent class method, it can use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the parent class code. 9. DYNAMIC METHOD DISPATCH Dynamic Method Dispatch  Method Overriding is an example of runtime polymorphism.  When a parent class reference points to the child class object then the call to the overridden method is determined at runtime, because during method call which method(parent class or child class) is to be executed is determined by the type of object.  This process in which call to the overridden method is resolved at runtime is known as dynamic method dispatch. Lets see an example to understand this: class ABC{ //Overridden method public void disp() { System.out.println("disp() method of parent class"); } } class Demo extends ABC{ //Overriding method public void disp(){ System.out.println("disp() method of Child class"); } public void newMethod(){
  • 36. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 36 System.out.println("new method of child class"); } public static void main( String args[]) { /* When Parent class reference refers to the parent class object * then in this case overridden method (the method of parent class) * is called. */ ABC obj = new ABC(); obj.disp(); /* When parent class reference refers to the child class object * then the overriding method (method of child class) is called. * This is called dynamic method dispatch and runtime polymorphism */ ABC obj2 = new Demo(); obj2.disp(); } } Output: disp() method of parent class disp() method of Child class 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 Rules of method overriding in Java 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.
  • 37. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 37 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();
  • 38. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 38 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. Binding of overridden methods happen at runtime which is known as dynamic binding. 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. Super keyword in Method Overriding The super keyword is used for calling the parent class method/constructor. super.myMethod() calls the myMethod() method of base class while super() calls the constructor of base class. Let’s see the use of super in method Overriding. As we know that we we override a method in child class, then call to the method using child class object calls the overridden method. By using super we can call the overridden method as shown in the example below: class ABC{ public void myMethod() { System.out.println("Overridden method"); } } class Demo extends ABC{ public void myMethod(){ //This will call the myMethod() of parent class super.myMethod(); System.out.println("Overriding method"); }
  • 39. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 39 public static void main( String args[]) { Demo obj = new Demo(); obj.myMethod(); } } Output: Class ABC: mymethod() Class Test: mymethod() *************************** 10. ABSTRACT CLASSES ABSTRACT CLASSES  A class that is declared with abstract keyword, is known as abstract class in java.  It can have abstract and non-abstract methods (method with body).  Abstraction is a process of hiding the implementation details and showing only functionality to the user.  Abstraction lets you focus on what the object does instead of how it does it.  It needs to be extended and its method implemented. It cannot be instantiated. Example abstract class: abstract class A{} abstract method: A method that is declared as abstract and does not have implementation is known as abstract method. abstract void printStatus();//no body and abstract 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
  • 40. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 40 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"); } } //In real scenario, method is called by programmer or user 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  Abstract class having constructor, data member, methods  An abstract class can have data member, abstract method, method body, constructor and even main() method. Example2: File: TestAbstraction2.java //example of abstract class that have method body
  • 41. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 41 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
  • 42. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 42 { 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 Use of All Features of Abstract Class 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. Such a class determines the nature of the methods that the subclasses must implement.
  • 43. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 43 Here is the source code of the Java Program to Illustrate Use of All Features of Abstract Class. The Java program is successfully compiled and run on a Windows system. Example1: abstract class Operations { float a = 12, b = 6, c; abstract void add(); void subtract() { c = a - b; System.out.println("Result:"+c); } abstract void multiply(); void divide() { c = a / b; System.out.println("Result:"+c); } } public class Abstract_Demo extends Operations { @Override void add() { c = a + b; System.out.println("Result:"+c); } @Override void multiply() { c = a * b; System.out.println("Result:"+c); } public static void main(String[] args) { Abstract_Demo obj = new Abstract_Demo();
  • 44. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 44 obj.add(); obj.subtract(); obj.multiply(); obj.divide(); } } Output: $ javac Abstract_Demo.java $ java Abstract_Demo Result:18.0 Result:6.0 Result:72.0 Result:2.0 Example 2: abstract class Calculation { float a = 12, b = 6, c; abstract void add(); void subtract() { c = a - b; System.out.println("Result:"+c); } abstract void multiply(); void divide() { c = a / b; System.out.println("Result:"+c); } } public class AbstractionDemo extends Calculation { void add() {
  • 45. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 45 c = a + b; System.out.println("Result:"+c); } void multiply() { c = a * b; System.out.println("Result:"+c); } public static void main(String[] args) { AbstractionDemo obj = new AbstractionDemo; obj.add(); obj.subtract(); obj.multiply(); obj.divide(); } } 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 {
  • 46. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 46 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
  • 47. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 47 { void method2() { System.out.println("World"); } public static void main(String s[]) { C c=new C(); c.method1(); c.method2(); } } *************** 11. FINAL WITH INHERITANCE Using final with inheritance  During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throughout all the derived classes.  Note that it is not necessary to declare final methods in the initial stage of inheritance(base class always).  We can declare a final method in any subclass for which we want that if any other class extends this subclass, then it must follow the same implementation of the method as in that subclass. // Java program to illustrate // use of final with inheritance // base class abstract class Shape { private double width; private double height; // Shape class parameterized constructor public Shape(double width, double height) { this.width = width; this.height = height; }
  • 48. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 48 // getWidth method is declared as final // so any class extending // Shape can't override it public final double getWidth() { return width; } // getHeight method is declared as final // so any class extending Shape // can not override it public final double getHeight() { return height; } // method getArea() declared abstract because // it upon its subclasses to provide // complete implementation abstract double getArea(); } // derived class one class Rectangle extends Shape { // Rectangle class parameterized constructor public Rectangle(double width, double height) { // calling Shape class constructor super(width, height); } // getArea method is overridden and declared // as final so any class extending // Rectangle can't override it @Override final double getArea() { return this.getHeight() * this.getWidth(); } }
  • 49. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 49 //derived class two class Square extends Shape { // Square class parameterized constructor public Square(double side) { // calling Shape class constructor super(side, side); } // getArea method is overridden and declared as // final so any class extending // Square can't override it @Override final double getArea() { return this.getHeight() * this.getWidth(); } } // Driver class public class Test { public static void main(String[] args) { // creating Rectangle object Shape s1 = new Rectangle(10, 20); // creating Square object Shape s2 = new Square(10); // getting width and height of s1 System.out.println("width of s1 : "+ s1.getWidth()); System.out.println("height of s1 : "+ s1.getHeight()); // getting width and height of s2 System.out.println("width of s2 : "+ s2.getWidth()); System.out.println("height of s2 : "+ s2.getHeight()); //getting area of s1 System.out.println("area of s1 : "+ s1.getArea());
  • 50. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 50 //getting area of s2 System.out.println("area of s2 : "+ s2.getArea()); } } 12. PACKAGES AND INTERFACES: PACKAGES 1) Introduction to Packages What is Package in Java? A Package is a collection of related classes. It helps organize your classes into a folder structure and make it easy to locate and use them. More importantly, it helps improve re-usability.  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. Creating and Using Packages To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages. 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.
  • 51. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 51  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 There are two types of packages in java. They are: a) Standard Packages b) User Defined 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:
  • 52. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 52  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. //in the Graphic.java file public abstract class Graphic { . . . } //in the Circle.java file public class Circle extends Graphic implements Draggable { . . . } //in the Rectangle.java file public class Rectangle extends Graphic implements Draggable { . . . } //in the Draggable.java file public interface Draggable { . . . } 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. Worthy note on packages:  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.
  • 53. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 53  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:  Refer to the member by its long (qualified) name  Import the package member  Import the member's entire package 2) Syntax to declare packages How to Create PACKAGE in Java? Syntax:- package nameOfPackage;
  • 54. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 54 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. Step 1) Consider the following code, 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 Step 2) In next step, save this file as demo.java
  • 55. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 55 Step 3) In this step, we compile the file. The compilation is completed. A class file c1 is created. However, no package is created? Next step has the solution
  • 56. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 56 Step 4) Now we have to create a package, use the command javac –d . demo.java This command forces the compiler to create a package. The "." operator represents the current working directory. 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. Step 6) Compile the same file using the following code 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.
  • 57. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 57 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 Step 8) Compile the file As seen in below screenshot, it creates a sub-package p2 having class c1 inside the package.
  • 58. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 58 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. ***********************
  • 59. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 59 13. PACKAGES AND MEMBER ACCESS 13.1 Introduction to Packages Creating and Using Packages To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages. Definition: A package is a collection of related types providing access protection and name space management. 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. 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. //in the Graphic.java file public abstract class Graphic { . . . } //in the Circle.java file public class Circle extends Graphic implements Draggable { . . . } //in the Rectangle.java file public class Rectangle extends Graphic implements Draggable { . . . }
  • 60. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 60 //in the Draggable.java file public interface Draggable { . . . } 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; public class Circle extends Graphic implements Draggable { . . . } The Circle class is a public member of the graphics package. 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; public class Rectangle extends Graphic implements Draggable { . . .
  • 61. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 61 } Worthy note on packages:  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. 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:  Refer to the member by its long (qualified) name  Import the package member  Import the member's entire package
  • 62. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 62 Each is appropriate for different situations, as explained in the sections that follow. Referring to a Package Member by Name  So far, the examples in this tutorial have referred to types by their simple names, such as Rectangle.  You can use a package member's simple name if the code you are writing is in the same package as that member or if that member has been imported.  However, if you are trying to use a member from a different package and that package has not been imported, you must use the member's qualified name, which includes the package name. Here is the qualified name for the Rectangle class declared in the graphics package in the previous example. graphics.Rectangle You could use this long name to create an instance of graphics.Rectangle: graphics.Rectangle myRect = new 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. ************* 14. IMPORTING PACKAGES Importing a Package Member To import a specific member into the current file, put an import statement at the beginning of the file before any class or interface definitions but after the package statement, if there is one. Here's how you would import the Circle class from the graphics package created in the previous section.
  • 63. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 63 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. Importing an Entire Package To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character. import graphics.*; Now you can refer to any class or interface in the graphics package by its short name. Circle myCircle = new Circle(); Rectangle myRectangle = new Rectangle();  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. Example of java package The package keyword is used to create a package in java. //save as Simple.java package mypack;
  • 64. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 64 public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } } How to compile java package? If you are not using any IDE, you need to follow the syntax given below: javac -d directory javafilename 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). How to run java package program? You need to use fully qualified name e.g. mypack.Simple etc to run the class. To Compile: javac -d . Simple.java To Run: java mypack.Simple 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. ********************* 15. INTERFACES 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
  • 65. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 65 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> { // declare constant fields // declare methods that abstract // by default. } Relationship between classes and interfaces 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();
  • 66. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 66 obj.print(); } } Output: Hello Example: interfaceDrawable { void draw(); } class Rectangle implements Drawable { public void draw(){System.out.println("drawing rectangle"); } } class Circle implements Drawable { public void draw(){System.out.println("drawing circle");} } class TestInterface1{ public static void main(String args[]) { Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()d.draw(); } } Output: drawing circle Multiple inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known asmultiple inheritance. Example:
  • 67. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 67 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");} public static void main(String args[]){ A7 obj = new A7(); obj.print(); obj.show(); } } Output:
  • 68. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 68 Hell o Wel com e Interface inheritance A class implements interface but one interface extends another interface .Example: interface Printable{ void print(); } interface Showable extends Printable{void show(); } class TestInterface4 implements Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ TestInterface4 obj = new TestInterface4(); obj.print(); obj.show(); }} Output: Hell o Wel com e Nested Interface in Java An interface can have another interface i.e. known as nested interface.interface printable{ void print(); interface MessagePrintable{void msg(); } }
  • 69. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 69 Key points to remember about interfaces: 1) We can’t instantiate an interface in java. That means we cannot create the object of an interface 2) Interface provides full abstraction as none of its methods have body. On the other hand abstract class provides partial abstraction as it can have abstract and concrete(methods with body) methods both. 3) “implements” keyword is used by classes to implement an interface. 4) While providing implementation in class of any method of an interface, it needs to be mentioned as public. 5) Class that implements any interface must implement all the methods of that interface, else theclass should be declared abstract. 6) Interface cannot be declared as private, protected or transient. 7) All the interface methods are by default abstract and public. 8) Variables declared in interface are public, static and final by default.interface Try { int a=10; publicint a=10; public static final int a=10;final int a=10; static int a=0; } All of the above statements are identical. 9) Interface variables must be initialized at the time of declaration otherwise compiler will throwan error. interface Try { int x;//Compile-time error } Above code will throw a compile time error as the value of the variable x is not initialized at the time of declaration. 10) Inside any implementation class, you cannot change the variables declared in interface because by default, they are public, static and final. Here we are implementing the interface “Try” which has a variable x. When we tried to set the value for variable x we got compilation error as the variable x is public static final by default and final variables can not be re-initialized.class Sample implements Try {
  • 70. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 70 public static void main(String args[]) { x=20; //compile time error } } 11) An interface can extend any interface but cannot implement it. Class implements interfaceand interface extends interface. 12) A class can implement any number of interfaces. 13) If there are two or more same methods in two interfaces and a class implements bothinterfaces, implementation of the method once is enough. interface A { public void aaa(); } interface B { public void aaa(); } class Central implements A,B { public void aaa() { //Any Code here } public static void main(String args[]) { //Statements } } 14) A class cannot implement two interfaces that have methods with same name but differentreturn type. interface A { public void aaa(); } interface B { public int aaa(); } class Central implements A,B
  • 71. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 71 { public void aaa() // error { } public int aaa() // error { } public static void main(String args[]) { } } 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); } } Advantages of interface in java:  Without bothering about the implementation part, we can achieve the security of implementation  In java, multiple inheritance is not allowed, however you can use interface to make useof it as you can implement more than one interface. DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE ABSTRACT CLASS INTERFACE
  • 72. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 72 1) Abstract class can have abstract and non- abstract methods. Interface can have only abstract methods. Since Java 8, it can have default and static methods also. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. 6) An abstract class can extend another Java class and implement multiple Java interfaces. An interface can extend another Java interface only. 7) An abstract class can be extended using keyword extends. An interface class can be implemented using keyword implements 8) A Java abstract class can have class members like private, protected, etc. Members of a Java interface are public by default. 9)Example: public abstract class Shape{ public abstract void draw(); } Example: public interface Drawable{ void draw(); } ************************