Unit 2
Unit 2
JAVA PROGRAMMING
UNIT - II
UNIT - 2
2
Syllabus
A Closer Look at Methods and Classes: Overloading
Methods, Overloading Constructors, Using Objects as
Parameters, A Closer Look at Argument Passing,
Returning Objects, Recursion, Introducing Access
Control, understanding static, introducing final,
Introducing Nested and Inner Classes, Exploring the
String Class, Using Command-Line Arguments.
Inheritance: Inheritance Basics, Using super, Creating
a Multilevel Hierarchy, When Constructors Are
Executed, Method Overriding.
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Overloading Methods
3
In Java it is possible to define two or more methods within the same class
that share the same name, as long as their parameter declarations are
different. When this is the case, 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.
When an overloaded method is invoked, Java uses the type and/or number
of arguments as its guide to determine which version of the overloaded
method to actually call.
Thus, overloaded methods must differ in the type and/or number of their
parameters. While overloaded methods may have different return types,
the return type alone is insufficient to distinguish two versions of a
method.
When Java encounters a call to an overloaded method, it simply executes
the version of the
Dr Yogish method
H K, whose
Professor, Dept. parameters
of ISE, match the arguments used in
RIT, Bengaluru -54.
the call.
Overloading Methods …Example
4
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("double a: " + a);
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Overloading Methods …Example
5
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
ob.test(123.25);
}
}
class Box {
double width, height, depth;
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Continue …
7
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using Objects as Parameters
9
So far, we have only been using simple types as parameters to methods. However, it is
both correct and common to pass objects to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if obj is equal to the invoking object
boolean equals(Test obj) {
if(a == obj.a && b == obj.b)
return true;
else
return false;
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using Objects as Parameters …
10
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
A Closer Look at Argument Passing
11
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void fun(Test obj) {
obj.a *= 2;
obj.b /= 2;
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Call by reference …example…
16
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.fun(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after
Dr Yogish H K, call:
Professor,30
Dept.10
of ISE, RIT, Bengaluru -54.
Recursion
17
class Factorial {
int fact(int n) {
int result;
if(n==1)
return 1;
result = n* fact(n-1);
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial obj = new Factorial();
System.out.println("Factorial of 3 is " + ob.fact(3));
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Introducing Access Control
19
As you know, encapsulation links data with the code that manipulates it.
However, encapsulation provides another important attribute: access control.
Through encapsulation, you can control what parts of a program can access
the members of a class. By controlling access, you can prevent misuse.
Java’s access specifiers are public, private, and protected. Java also defines a
default access level. protected applies only when inheritance is involved.
When a member of a class is modified by the public specifier, then that
member can be accessed by any other code. When a member of a class is
specified as private, then that member can only be accessed by other members
of its class.
Now you can understand why main( ) has always been preceded by the public
specifier. It is called by code that is outside the program—that is, by the Java
run-time system. When no access specifier is used, then by default the
member of a class is public within its own package, but cannot be accessed
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
outside of its package.
Introducing Access Control …
20
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Introducing Access Control …
21
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 10; // These are OK, a and b may be accessed directly
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error! You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}
Static Methods
• The static keyword is used to create methods that
will exist independently of any instances created for
the class.
• Methods declared as static have several
restrictions:
• • They can only call other static methods.
• • They must only access static data.
• • They cannot refer to this or super in any way. (The
keyword super
Dr Yogish H relates
K, Professor, toRIT,inheritance)
Dept. of ISE, Bengaluru -54.
Example: shows a class that has a static method, some static
variables, and a static initialization block:
24
class UseStatic {
static int a = 3;
static int b;
static void fun(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
fun(42);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Continue…
25
As soon as the UseStatic class is loaded, all of the static statements are
run.
First, a is set to 3,
then the static block executes, which prints a message and then initializes
b to a*4 or 12.
Then main( ) is called, which calls meth( ), passing 42 to x. The three
println( ) statements refer to the two static variables a and b, as well as to
the local variable x.
Outside of the class in which they are defined, static methods and
variables can be used independently of any object. To do so, you
need only specify the name of their class followed by the dot
operator.
For example, if you wish to call a static method from outside its
class, you can do so using the following general form:
classname.method( ) ;
Here, classname is the name of the class in which the static
method is declared.
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Here is the output of this program:
a = 42
b = 99 Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Introducing final
28
class Outer {
int o_x = 10;
class Inner {
int i_y = 5;
}
}
class Main {
public static void main(String[] args) {
Outer Outerob = new Outer();
Outer.Inner Innerob = Outerob.new Inner();
System.out.println(Innerob.i_y + Outerob.o_x);
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
}
Static Inner Class : An inner class can also be static, which
means that you can access it without creating an object of the outer
class.
33
class Outer {
int o_x = 10;
static class Inner {
int i_y = 5;
}
}
class Main {
public static void main(String[] args) {
Outer Outerob = new Outer();
//Outer.Inner Innerob = Outerob.new Inner();
Outer.Inner Innerob = new Outer.Inner();
System.out.println(Innerob.i_y + Outerob.o_x);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Exploring the String Class
34
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " + strOb1.length());
System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
}
Output
41
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
java CommandLine this is a test 100 -1
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1 Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Inheritance
44
// Create a superclass.
class A {
int i; // public by default
private int k; // private to A
void setij(int x, int y) {
i = x;
k = y;
}
}
// A’s k is not accessible here.
class B extends A {
int total;
void sum() {
total = i + k; // ERROR, k is not accessible here
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
}
Using super
50
class B extends A {
int j;
B(int b1,int b2 {
super(b1);
j=b2;
}
void showj() {
System.out.println(“j: " + j);
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super ….
53
class SimpleInheritance {
public static void main(String args[]) {
B subOb = new B(5,10);
System.out.println("Contents of subOb: ");
subOb.showi();
subOb.showj();
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super - member names of a subclass hide
members by the same name in the superclass
54
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following output:
i in superclass: 1
i in subclass: 2
Although the instance variable i in B hides the i in A, super
allows access to the i defined in the superclass. As you will see,
super can also be used to call methods that are hidden by a
subclass Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super …
57
class B extends A {
int j ;
B(int b1, int b2) {
i=b1;
j = b2;
}
void show() {
super.show();
System.out.println("j in subclass: " + j);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super …
59
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
class A { int i;
void showi() {
System.out.println("i " + i );
}
}
class B extends A { int j;
void showj() {
System.out.println(“j: " + j);
}
}
class C extends B { int k;
void showk() {
System.out.println("k: " + k);
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Example
62
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class MultilevelInheritance {
public static void main(String args[]) {
C subOb = new C();
subOb.i = 7; subOb.j = 8; subOb.k =9 ;
System.out.println("Contents of subOb: ");
subOb.showi(); subOb.showj(); subOb.showk();
System.out.println("Sum of i ,j and k in subOb:");
subOb.sum();
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
When Constructors are Called
63
class A {
A() {
System.out.println(" A's constructor.");
}
}
class B extends A {
B() {
System.out.println("B's constructor.");
}
}
class C extends B {
C() {
System.out.println("C's constructor.");
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
When Constructors Are Called ..Example
65
class CallingCons {
public static void main(String args[]) {
C ob = new C();
}
}
Output:
A’s constructor
B’s constructor
C’s constructor
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Method Overriding
66
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void 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;
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
….
68