CS3391 Unit-2
CS3391 Unit-2
Method Overloading is a feature in Java that allows a class to have more than one
methods having same name, but with different signatures (Each method must have
different number of parameters or parameters having different types and orders).
Advantage:
Method Overloading increases the readability of the program.
Provides the flexibility to use similar method with different parameters.
In order to overload a method, the argument lists of the methods must differ in either of
these:
return min;
}
public static double minFunction(int n1, double n2)
{
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Minimum(11,6,3) = 3
Minimum(7.3,9.4) = 7.3
Minimum(11,7.3) = 7.3
Note:-
Method overloading is not possible by changing the return type of the method
because of ambiguity that may arise while calling the method with same
parameter list with different return type.
Example:
class Add
{
static int sum(int a, int b)
{
return a+b;
}
static float sum(int a, int b)
4
{
return a+b;
}
public static void main(String arg[])
{
System.out.println(sum(10,20));
System.out.println(sum(15,25));
}
}
Output:
Compile by: javac TestOverloading3.java
class Overloading
{
void sum(int a, float b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
OUTPUT:
40.0
165.0
60
6
Returning Objects:
In Java, a method can return any type of data. Return type may any primitive data type
or class type (i.e. object). As a method takes objects as parameters, it can also return
objects as return value.
Example:
class Add
{
int num1,num2,sum;
Add ob3=calculateSum(ob1,ob2);
System.out.println("Object 1 -> Sum = "+ob1.sum);
8
OUTPUT:
Definition:
Benefits:
1. Name control
2. Access control
3. Code becomes more readable and maintainable because it locally group related
classes in one place.
1) Nested class can access all the members (data members and methods) of
outer class including private.
2) Nested classes are used to develop more readable and maintainable code.
3) Code Optimization: It requires less code to write.
Type Description
Member Inner Class A class created within class and outside method.
A class created for implementing interface or
Anonymous Inner Class extending class. Its name is decided by the java
compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.
10
A non-static class that is created inside a class but outside a method is called member
inner class.
Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
In this example, we are creating msg() method in member inner class that is accessing
the private data member of outer class.
1. class TestMemberOuter1
2. {
3. private int data=30;
4. class Inner
5. {
6. void msg()
7. {
8. System.out.println("data is "+data);
9. }
10. }
11. public static void main(String args[])
12. {
13. TestMemberOuter1 obj=new TestMemberOuter1();
14. TestMemberOuter1.Inner in=obj.new Inner();
15. in.msg();
16. }
17. }
Output:
data is 30
11
Output:
nice fruits
1. interface Eatable
2. {
3. void eat();
12
4. }
5. class TestAnnonymousInner1
6. {
7. public static void main(String args[])
8. {
9. Eatable e=new Eatable()
10. {
11. public void eat(){System.out.println("nice fruits");
12. }
13. };
14. e.eat();
15. }
16. }
Output:
nice fruits
A class i.e. created inside a method is called local inner class in java. If you want to
invoke the methods of local inner class, you must instantiate this class inside the
method.
Output:
30
50
Properties:
1. Completely hidden from the outside world.
2. Cannot access the local variables of the method (in which they are defined), but
the local variables has to be declared final to access.
A static class i.e. created inside a class is called static nested class in java. It cannot
access non-static data members and methods. It can be accessed by outer class name.
o It can access static data members of outer class including private.
o Static nested class cannot access non-static (instance) data member or method.
1. class TestOuter1
2. {
3. static int data=30;
4. static class Inner
5. {
6. void msg()
14
7. {
8. System.out.println("data is "+data);
9. }
10. }
1. public static void main(String args[])
12. {
13. TestOuter1.Inner obj=new TestOuter1.Inner();
14. obj.msg();
15. }
16. }
Output:
data is 30
If you have the static member inside static nested class, you don't need to create
instance of static nested class.
1. class TestOuter2{
2. static int data=30;
3. static class Inner
4. {
5. static void msg()
6. {
7. System.out.println("data is "+data);
8. }
9. }
10. public static void main(String args[])
11. {
12. TestOuter2.Inner.msg();//no need to create the instance of static nested
class
13. }
14. }
Output:
data is 30
15
2.4: Inheritance
Definition:
Inheritance is a process of deriving a new class from existing class, also called as
“extending a class”. When an existing class is extended, the new (inherited) class
has all the properties and methods of the existing class and also possesses its own
characteristics.
The class whose property is being inherited by another class is called “base class”
(or) “parent class” (or) “super class”.
The class that inherits a particular property or a set of properties from the base class
is called “derived class” (or) “child class” (or) “sub class”.
Extended to
Class B
Derived
Properties and methods
of Class A + B’s own
properties and methods
Subclasses of a class can define their own unique behaviors and yet share some of
the same functionality of the parent class.
ADVANTAGES OF INHERITANCE:
Reusability of Code:
Inheritance is mainly used for code reusability (Code reusability means
that we can add extra features to an existing class without modifying it).
Effort and Time Saving:
The advantage of reusability saves the programmer time and effort. Since
the main code written can be reused in various situations as needed.
Increased Reliability:
The program with inheritance becomes more understandable and easily
maintainable as the sub classes are created from the existing reliably
working classes.
16
“extends” KEYWORD:
Inheriting a class means creating a new class as an extension of another class.
The extends keyword is used to inherit a class from existing class.
The general form of a class declaration that inherits a superclass is shown here:
Syntax:
[access_specifier] class subclass_name extends superclass_name
{
// body of class
}
In the above example, Vehicle is the super class or base class that holds the
common property of Car and Bike. Car and Bike is the sub class or derived class that
inherits the property of class Vehicle extends is the keyword used to inherit a class.
17
TYPES OF INHERITACE:
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
Note: The following inheritance types are not directly supported in Java.
4. Hierarchical Inheritance
5. Hybrid Inheritance
18
1. SINGLE INHERITANCE
The process of creating only one subclass from only one super class is known as Single
Inheritance.
Only two classes are involved in this inheritance.
The subclass can access all the members of super class.
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14.}
15.class TestInheritance
16.{
17. public static void main(String args[])
18. {
19. Dog d=new Dog();
20. d.bark();
21. d.eat();
22. }
23.}
Output:
$java TestInheritance
barking...
eating...
19
2. MULTILEVEL INHERITANCE:
The process of creating a new sub class from an already inherited sub class
is known as Multilevel Inheritance.
Multiple classes are involved in inheritance, but one class extends only one.
The lowermost subclass can make use of all its super classes' members.
Multilevel inheritance is an indirect way of implementing multiple inheritance.
Example: Animal Dog BabyDog
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14. }
15. class BabyDog extends Dog
16. {
17. void weep()
18. {
19. System.out.println("weeping...");
20. }
21. }
22. class TestInheritance2
23. {
24. public static void main(String args[]) {
25. BabyDog d=new BabyDog();
26. d.weep();
27. d.bark();
28. d.eat();
29. }
30. }
20
Output:
$java TestInheritance2
weeping...
barking...
eating..
3. HIERARCHICAL INHERITANCE
The process of creating more than one sub classes from one super class is called
Hierarchical Inheritance.
Animal
Dog Cat
Example:
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14. }
15. class Cat extends Animal
16. {
17. void meow()
18. {
19. System.out.println("meowing...");
20. }
21
21. }
22. class TestInheritance3
23. {
24. public static void main(String args[])
25. {
26. Cat c=new Cat();
27. c.meow();
28. c.eat();
29. //c.bark();//C.T.Error
30. }
31. }
Output:
meowing...
eating...
The private members of a class cannot be directly accessed outside the class. Only
methods of that class can access the private members directly. However, sometimes it
may be necessary for a subclass to access a private member of a superclass. If you make
a private member public, then anyone can access that member. So, if a member of a
superclass needs to be (directly) accessed in a subclass then you must declare that
member protected.
Following program illustrates how the methods of a subclass can directly access a
protected member of the superclass.
Consider two kinds of shapes: rectangles and triangles. These two shapes have certain
common properties height and a width (or base).
This could be represented in the world of classes with a class Shapes from which we
would derive the two other ones : Rectangle and Triangle
Program : (Shape.java)
2
23
Program : (Rectangle.java)
public class Rectangle extends Shape
{
public double getArea()
{
return height * width; //accessing protected members
}
}
Program : (Triangle.java)
public class Triangle extends Shape
{
public double getArea()
{
return height * width / 2; //accessing protected members
}
}
Program : (TestProgram.java)
Output :
Area of rectangle : 20.0
Area of triangle : 25.0
In Java, constructor of base class with no argument gets automatically called in derived
class constructor.
Example:
class A
{
A()
{ System.out.println(“ Inside A’s Constructor”); }
}
class B extends A
{
B()
25
Inside A’s
Constructor Inside B’s
Constructor Inside C’s
Constructor
Program Explanation:
In the above program, we have created three classes A, B and C using
multilevel inheritance concept. Here, constructors of the three classes are called in the
order of derivation. Since super() must be the first statement executed in subclass’s
constructor, this order is the same whether or not super() is used. If super() is not
used, then the default or parameterless constructor of each superclass will be executed.
When inheriting from another class, super() has to be called first in the constructor. If
not, the compiler will insert that call. This is why super constructor is also invoked when
a Sub object is created.
After compiler inserts the super constructor, the sub class constructor looks like the
following:
B()
{
super();
System.out.println("Inside B’s Constructor");
}
C()
{
super();
26
Super is a special keyword that directs the compiler to invoke the superclass
members. It is used to refer to the parent class of the class in which the keyword is
used.
super keyword is used for the following three purposes:
1. To invoke superclass constructor.
2. To invoke superclass members variables.
3. To invoke superclass methods.
Example:
class A // super class
{
int i;
A(String str) //superclass constructor
{
System.out.println(" Welcome to "+str);
}
void show() //superclass method
{
System.out.println(" Thank You!");
}
}
class B extends A
{
int i; // hides the superclass variable
'i'. B(int a, int b) // subclass
constructor
{
super("Java Programming"); // invoking superclass constructor
super.i=a; //accessing superclass member variable
i=b;
}
// Mehtod overriding
@Override
void show()
{
System.out.println(" i in superclass : "+super.i);
System.out.println(" i in subclass : "+i);
super.show(); // invoking superclass
method
28
}
}
public class UseSuper {
public static void main(String[] args) {
B objB=new B(1,2); // subclass object construction
objB.show(); // call to subclass method show()
}
}
Output:
Welcome to Java Programming
i in superclass : 1
i in subclass : 2
Thank You!
Program Explanation:
In the above program, we have created the base class named A that contains a instance
variable ‘i’ and a method show(). Class A contains a parameterized constructor that
receives string as a parameter and prints that string. Class B is a subclass of A which
contains a instance variable ‘i’ ( hides the superclass variable ‘i’) and overrides the
superclass method show(). The subclass defines the constructor with two parameters a
and b. The subclass constructor invokes the superclass constructor super(String) by
passing the string “Java Programming” and assigns the value a to the superclass
variable(super.i=a) and b to the subclass variable. The show() method of subclass
prints the values of ‘i’ form both superclass and subclass & invokes the superclass
method as super.show().
In the main class, object for subclass B is created and the object is used to invoke
show() method of subclass.
When a method in a subclass has the same name and type signature as a method
in its superclass, then the method in subclass is said to override a method in the
superclass.
Example:
class Bank
{
int getRateOfInterest()// super class method
{
return 0;
}
29
}
class Axis extends Bank// subclass of bank
{
int getRateOfInterest()// overriding the superclass method
{
return 6;
}
}
class ICICI extends Bank// subclass of Bank
{
int getRateOfInterest()// overriding the superclass method
{
return 15;
}
}
// Mainclass
class BankTest
{
public static void main(String[] a)
{
Axis a=new Axis();
ICICI i=new ICICI();
// following method call invokes the overridden method of subclass AXIS
System.out.println(“AXIS: Rate of Interest = “+a.getRateOfInterest());
Output:
class A {
void callme() {
System.out.println(“Inside A’s callme method”);
}
}
class B extends A {
//override callme()
void callme() {
System.out.println(“Inside B’s callme method”);
}
}
class C extends A
{
//override callme()
void callme() {
System.out.println(“Inside C’s callme method”);
}
}
class Dispatch
{
public static void main(String args[])
{
A a=new A(); //object of type A
B b=new B(); //object of type B
C c=new C(); //object of type C
A r;// obtain a reference of type A
31
In Method Overloading,
In Method Overriding, sub
Methods of the same class
class have the same method
shares the same name but each
with same name and exactly
Definition method must have different
the same number and type of
number of parameters or
parameters and same return
parameters having different
type as a super class.
types and order.
Method Overloading means Method Overriding means
more than one method shares method of base class is re-
Meaning
the same name in the class but defined in the derived class
having different signature. having same signature.
Method Overloading is to “add” Method Overriding is to
Behavior or “extend” more to method’s “Change” existing behavior of
behavior. method.
For example sending sms, you just type the text and send the message. You don't
know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Abstract Classes:
Example:
abstract class GraphicObject
{ int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
Abstract Methods:
Write a Java program to create an abstract class named Shape that contains 2
integers and an empty method named PrintArea(). Provide 3 classes named
Rectangle, Triangle and Circle such that each one of the classes extends the
class Shape. Each one of the classes contain only the method PrintArea() that
prints the area of the given shape.
}
}
class Triangle extends shape
{
void printArea()
{
System.out.println("Area of Triangle is " + (x * y) / 2);
}
}
class Circle extends shape
{
void printArea()
{
System.out.println("Area of Circle is " + (22 * x * x) / 7);
}
}
class abs
{
public static void main(String[] args)
{
Rectangle r = new Rectangle();
r.x = 10;
r.y = 20;
r.printArea();
System.out.println("-------------------------------------------------");
System.out.println("-------------------------------------------------");
37
System.out.println("-------------------------------------------------");
}
}
Output:
D:\>javac abs.java
D:\>java abs
Area of Rectangle is 200
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
Area of Triangle is 525
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
Area of Circle is 12
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
1. Final Variable:
Any variable either member variable or local variable (declared inside method or
block) modified by final keyword is called final variable.
The final variables are equivalent to const qualifier in C++ and #define directive
in C.
Syntax:
38
Example:
final int MAXMARKS=100;
final int PI=3.14;
There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can never
be changed.
1. class Bike
2. {
3. final int speedlimit=90;//final variable
4. void run( )
5. {
6. speedlimit=400;
7. }
8. public static void main(String args[])
9. {
10. Bike obj=new Bike();
11. obj.run();
12. }
13.}
Output: Compile Time Error
NOTE: Final variables are by default read-only.
2. Final Methods:
Final keyword in java can also be applied to methods.
A java method with final keyword is called final method and it cannot be
overridden in sub-class.
If a method is defined with final keyword, it cannot be overridden in the
subclass and its behaviour should remain constant in sub-classes.
Syntax:
final return_type function_name(parameter_list)
{
// method body
}
39
1. class Bike
2. {
3. final void run()
4. {
5. System.out.println("running");
6. }
7. }
8. class Honda extends Bike
9. {
10. void run()
11. {
12. System.out.println("running safely with 100kmph");
13. }
14. public static void main(String args[])
15. {
16. Honda honda= new Honda();
17. honda.run();
18. }
19.}
Output:
D:\>javac Honda.java
Honda.java:9: error: run() in Honda cannot override run() in Bike
void run()
^
overridden method is final
1 error
3. Final Classes:
Java class with final modifier is called final class in Java and they cannot
be sub-classed or inherited.
Syntax:
final class class_name
{
// body of the class
}
Several classes in Java are final e.g. String, Integer and other wrapper classes.
40
Points to Remember:
2.10: PACKAGES
Definition:
Advantage of Package:
Package is used to categorize the classes and interfaces so that they can be easily
maintained.
Package provides access protection.
Package removes naming collision.
To bundle classes and interface
The classes of one package are isolated from the classes of another package
Provides reusability of code
We can create our own package or extend already available package
42
Java package created by user to categorize their project's classes and interface
are known as user-defined packages.
When creating a package, you should choose a name for the package.
Put a package statement with that name at the top of every source file that
contains the classes and interfaces.
The package statement should be the first line in the source file.
There can be only one package statement in each source file
Syntax:
package package_name.[sub_package_name];
public class classname
{ ……..
……..
}
Example:
package pack;
public class class1 {
public static void greet()
{ System.out.println(“Hello”); }
}
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Syntax:
import package1[.package2][.package3].classname or *;
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
Using packagename.classname
If you import package.classname then only declared class of this package will
be accessible.
package pack;
public class
greeting{ public static
void greet()
{ System.out.println(“Hello! Good Morning!”); }
}
package Factorial;
public class FactorialClass
{
44
Output:
F:\>java ImportClass
Enter a Number:
5
Hello! Good Morning!
Factorial of 5 = 120
Power(5,2) = 25.0
Access level modifiers determine whether other classes can use a particular field or
invoke a particular method.
45
The following table shows the access to members permitted by each modifier.
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
The following figure shows the four classes in this example and how they are related.
Figure: Classes and Packages of the Example Used to Illustrate Access Levels
46
The following table shows where the members of the Alpha class are visible for each of
the access modifiers that can be applied to them.
Visibility
Modifier Alpha Beta Alphasub Gamma
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Example:
Z:\MyPack\FirstClass.java
package MyPack;
Z:\MyPack2\SecondClass.java
package MyPack2;
import MyPack.FirstClass;
class SecondClass extends FirstClass
{ void method()
{
System.out.println(i); // No Error: Will print "I am public variable".
System.out.println(j); // No Error: Will print “I am protected variable”.
System.out.println(k); // Error: k has private access in FirstClass
System.out.println(r); // Error: r is not public in FirstClass; cannot be accessed
// from outside package
}
47
Output:
I am public variable
I am protected variable
2.11: INTERFACES
Definition:
An interface is a collection of method definitions (without implementations)
and constant values. It is a blueprint of a class. It has static constants and abstract
methods.
Defining Interfaces:
An interface is defined much like a class. The keyword “interface” is used to
define an interface.
Where,
Access_specifer : either public or none.
Name: name of an interface can be any valid java identifier.
Variables: They are implicitly public, final and static, meaning that they cannot be
changed by the implementing class. They must be initialized with a constant
value.
49
Methods: They are implicitly public and abstract, meaning that they must be declared
without body and defined only by the implementing class.
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
Once an interface has been defined, one or more classes can implement that
interface.
A class uses the implements keyword to implement an interface.
The implements keyword appears in the class declaration following the extends
portion of the declaration.
Syntax:
Rules:
1. If a class implements an interface, then it must provide implementation for all the
methods defined within that interface.
2. A class can implement more than one interfaces by separating the interface
names with comma(,).
3. A class can extend only one class, but implement many interfaces.
4. An interface can extend another interface, similarly to the way that a class can
extend another class.
5. If a class does not perform all the behaviors of the interface, the class must
declare itself as abstract.
Example:
/* File name : Super.java */
interface Super
{
final int x=10;
void print();
}
/* File name : Sub.java */
class Sub implements Super
{
int y=20;
x=100 //ERROR; cannot change modify the value of final variable
Output:
$java sample
X = 10
Y = 20
X = 10
Y = 20
52
Member variables:
Can be only public and are by default.
By default are static and always static
By default are final and always final
Methods:
Can be only public and are by default.
Cannot be static
Cannot be Final
Properties of Interfaces:
1. Interfaces are not classes. So the user can never use the new operator to
instantiate an interface.
Example: interface super {}
X=new Super() // ERROR
2. The interface variables can be declared, even though the interface objects
can’t be constructed.
Super x; // OK
3. An interface variable must refer to an object of a class that implements the
interface.
4. The instanceOf() method can be used to check if an object implements an
interface.
5. A class can extend only one class, but implement many interfaces.
6. An interface can extend another interface, similarly to the way that a class
can extend another class.
7. All the methods in the interface are public and abstract.
8. All the variable in the interface are public, static and final.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can
extend another class.
The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
Syntax:
[accessspecifier] interface InterfaceName extends interface1, interface2,…..
{
53
Rule: When a class implements an interface that inherits another interface it must
provide implementation for all the methods defined within the interface inheritance
chain.
Example:
interface A
{
void method1();
}
/* One interface can extend another interface. B now has two abstract methods */
interface B extends A
{
void method2();
}
// This class must implement all the methods of A and B
Output:
F:\> java MyClass
--Method from Interface: A—
--Method from Interface: B—
--Method of the class: MyClass--
54
55
Class Interface
The class is denoted by a keyword class The interface is denoted by a keyword
interface
The class contains data members and The interfaces may contain data members
methods. but the methods are defined in and methods but the methods are not
the class implementation. thus class defined. the interface serves as an outline
contains an executable code for the class
By creating an instance of a class the class you cannot create an instance of an
members can be accessed interface
The class can use various access specifiers The interface makes use of only public
like public, private or protected access specifier
The members of a class can be constant or The members of interfaces are always
final declared as final
1. interface Bank
2. {
3. float rateOfInterest();
4. }
5. class SBI implements Bank
6. {
7. public float rateOfInterest()
8. {
9. return 9.15f;
10. }
11. }
12. class PNB implements Bank
13. {
14. public float rateOfInterest()
15. {
16. return 9.7f;
17. }
18. }
19. class TestInterface2
20. {
21. public static void main(String[] args)
22. {
23. Bank b=new SBI();
24. System.out.println("ROI: "+b.rateOfInterest());
25. }
26. }
Output:
ROI: 9.15