You are on page 1of 141

UNIT 1

BASIC CONCEPTS

© Ganapathi Nayak K
1
Basic Concepts

Features of Java
Object Oriented Language
 True OOPL
 Reusability (built-in classes in packages)
Compiled and Interpreted
 Compiler generates bytecode instructions
 Interpreter generates machine instructions executable on the particular machine
Platform-independent (Architecture-Neutral) and Portable
 Change in program not required
Robust and Secure
 Compile-time and run-time check for data types
 Exception handling mechanism
Multi-threaded
 Do many things concurrently with synchronization

© Ganapathi Nayak K
2
Basic Concepts

OOP Principles
Encapsulation
 Mechanism that binds together code and data it manipulates, and keeps it safe from
outside interference and misuse
Inheritance
 Process by which one object acquires the properties of another object
Polymorphism
A feature that allows one interface to be used for a general class of actions

© Ganapathi Nayak K
3
Program Structure

Documentation Section

Package Statements

Import Statements

Interface Statements

Class Definitions

Main Method Class


{
Main Method Definition
}

© Ganapathi Nayak K
4
Data Types and Variables

Java Keywords

abstract continue for new switch


assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while

const and goto are reserved but not used


Comments
// for single line, /* and */ for multiline

© Ganapathi Nayak K
5
Data Types and Variables

Primitive Data Types


Integers: byte 8, short 16, int 32 and long 64
Java does not support unsigned integers

Name Width in bits Range


long 64 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
int 32 -2,147,483,648 2,147,483,647
short 16 -32,768 32,767
byte 8 -128 127

Floating-Point: float 32, double 64


Name Width in bits Approximate Range
double 64 4.9e-324 1.8e+308
float 32 1.4e-045 3.4e+038

Character: char 16 (Unicode)


Boolean: boolean 8 (true, false)
© Ganapathi Nayak K
6
Data Types and Variables

Reference Data Types


Created using defined constructors of the classes.
Used to access objects.
Declared to be of a specific type that cannot be changed.
Examples: Class objects, array variables etc.
Default value of any reference variable is null.

© Ganapathi Nayak K
7
Data Types and Variables

Literals
A sequence of characters (digits, letters and other characters) that
represent constant values to be stored in variables.
Categories of literals
Integer Literals : decimal, binary (0B), octal (0) and hexadecimal (0x)
– Assign integer literal to byte or short – no error if within range
– Long literal end with L
Floating-Point Literals: Standard and Scientific notation
– Default is double precision (Optional D or d can be used)
– Float literal end with F or f
Boolean Literals: Values true and false (not same as 1 and 0)
Character Literals: Unicode character set
– Visible ASCII characters used within quotes (E.g., ‘a’, ‘6’)
– Others using escape sequences (E.g., ‘\n’, ‘\b’, ‘\”’)
String Literals: Enclose within double quotes
© Ganapathi Nayak K
8
Data Types and Variables

Identifiers
Used for naming variables, methods, classes, interfaces and packages
Sequence of uppercase and lowercase letters, numbers, underscore and
dollar-sign characters
Keywords cannot be used
Must not begin with a number
Case sensitive
Conventions:
 Variables and Methods: Mixed Case
– first letter of each word except the first word in uppercase, others in lowercase
 Interfaces and Classes: Camel Case
– first letter of each word in uppercase, others in lowercase
 Packages: Lower Case

© Ganapathi Nayak K
9
Data Types and Variables

Variables
Syntax: type identifier [= value][, identifier [=value]…];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte z = 10;
double pi = 3.14159;
float k = 3.56f;
char x = ‘x’;
Types of variables
 Local variables
 Instance variables
 Class / Static variables

© Ganapathi Nayak K
10
Data Types and Variables

Local Variables
Declared in methods, constructors or blocks
Created when a method, constructor or block is entered and destroyed
when the method, constructor or block is exited
Visible only within the method, constructor or block
No default values; an initial value should be assigned before its first use
Access specifiers cannot be used

© Ganapathi Nayak K
11
Data Types and Variables

Instance (Member) Variables


Declared in a class, but outside a method, constructor or block
Created when an object is created and destroyed when the object is
destroyed
Access specifiers can be used
Visible in all the methods, constructors and blocks in the class
Visibility for the subclasses can be specified using the access modifiers
Have default values (Numbers: 0, Boolean: false, Object references: null)
Can be accessed directly by using the variable name inside the class;
however, within static methods and other classes (when it is given
accessibility) should be called using the fully qualified name
objectReference.variableName

© Ganapathi Nayak K
12
Data Types and Variables

Static / Class Variables


Declared with the keyword static in a class, but, outside a method,
constructor or a block
There will be only one copy of the class variable per class, regardless of how
many objects are created
Created when the program starts and destroyed when the program
terminates
Visibility is similar to instance variables
Default values are same as for instance variables
Can be accessed by using the class name
className.variableName

© Ganapathi Nayak K
13
Data Types and Variables

Scope and Lifetime of Variables


Variables can be declared in any block
Scope is defined by a class and a method
Scope defined by a class (will be dealt with later in ‘class’)
Scope defined by a method: Between {}, Formal parameters
Lifetime is confined to its scope
Scopes can be nested
Same variable can not be repeated in nested scopes
Variables in outer scope available in inner scope

© Ganapathi Nayak K
14
Data Types and Variables

Scope and Lifetime of Variables (Continued …)


Example: void test()
{
int x = 10;
if (x == 10)
{
int y = 20; // y = 20
x = y * 2; // x = 40
System.out.println(“x = ” + x);
System.out.println(“y = ” + y);
}
y = 100; // cannot find symbol
x = x + 15;
System.out.println(“x = ” + x);
}

© Ganapathi Nayak K
15
Data Types and Variables

Type Conversion and Casting


Automatic Conversion: Conditions
 Two types are compatible
– Numeric types (integer and floating-point) are compatible with each other
 Destination type is larger than source type
Examples:
 byte to int – possible
 Any numeric type to char/boolean – not possible
 char and boolean – not compatible with each other
Automatic type conversion is done when a literal integer constant is stored
into variables of type byte, short, long and char

© Ganapathi Nayak K
16
Data Types and Variables

Type Conversion and Casting (Continued …)


Widening primitive conversions

→ byte short char int long float double

byte Yes Yes Yes Yes Yes

short Yes Yes Yes Yes

char Yes Yes Yes Yes

int Yes Yes Yes

long Yes Yes

float Yes

double

© Ganapathi Nayak K
17
Data Types and Variables

Type Conversion and Casting (Continued …)


Narrowing primitive conversions

→ byte short char int long float double

byte

short Yes Yes

char Yes Yes

int Yes Yes Yes

long Yes Yes Yes Yes

float Yes Yes Yes Yes Yes

double Yes Yes Yes Yes Yes Yes

© Ganapathi Nayak K
18
Data Types and Variables

Type Conversion and Casting (Continued …)


Casting incompatible types
 Syntax: (target-type) value
 Example: int a; byte b; b = (byte) a;
Truncation in case of floating-point values
 Example: 1.23 assigned to integer → 1 (0.23 truncated)

Examples:
byte b;
int i = 257;
double d = 323.142;
b = (byte) i; // 1 (remainder of special type of division)
i = (int) d; // 323 (0.142 lost)
b = (byte) d; // 67 (0.142 lost and reduced to modulo)

Note: If i = 255, then “b = (byte) i” results in -1


© Ganapathi Nayak K
19
Data Types and Variables

Automatic Type Promotion in Expressions


Depends on precision required
Precision required by an intermediate value exceeds the range of either
operand
Example 1:
byte a = 40, b = 50, c = 100; int d = a * b / c;
– Result of a * b exceeds range of byte
– Promotes byte, short or char operand to int during evaluation
– a * b is performed using integers and …
Example 2:
byte b = 50; b = b * 2;
– Error, cannot assign an int to a byte (operands promoted to int)
– Use explicit type-casting
byte b = 50;
b = (byte) (b * 2);
© Ganapathi Nayak K
20
Data Types and Variables

Type Promotion Rules


All byte, short and char promoted to int
If one operand is a long, entire expression is promoted to long
If one operand is a float, entire expression is promoted to float
If any one of the operands is double, the result is double
Example:
byte b = 42; char c = ‘a’; short s = 1024;
int i = 50000; float f = 5.67f; double d = 0.1234;
double result = (f * b) + (i / c) – (d * s);
» In f * b, b promoted to float; result float
» In i / c, c promoted to int; result int
» In d * s, s promoted to double; result double
» float + int → float (int promoted to float)
» float – double → double (float promoted to double)

© Ganapathi Nayak K
21
Arrays

Basic Concepts of an Array


Arrays are dynamically created objects.
An array object contains a number of variables.
Number of variables may be zero (i.e., array is empty).
Variables contained in an array have no names
– They are referenced by array access expressions that use non-negative integer
index values (from 0 to n-1).
Array objects have a public instance variable called length, which gives
the number of elements in the array.

© Ganapathi Nayak K
22
Arrays

One-Dimensional Arrays
Syntax: type array-var[];
 Only declaration, memory not allocated
 Allocate memory using new operator
array-var = new type[size]
Example 1:
int one [];
one = new int [5];
Example 2:
int one [] = new int [5];

Example 3:
int one [] = {1, 2, 3, 4, 5};

© Ganapathi Nayak K
23
Arrays

Two-Dimensional Arrays
Syntax: type array-var[][];
 Only declaration, memory not allocated
 Allocate memory using new operator
array-var = new type[size][size]
Example 1:
int two [][];
two = new int [3][2];
Example 2:
int two [][] = new int [3][2];

Example 3:
int two [][] = {{1, 2}, {3, 4}, {5, 6}};

© Ganapathi Nayak K
24
Arrays

Two-Dimensional Arrays (Continued …)


Example 4:
int two [][] = new int [3][];
two [0] = new int [2];
two [1] = new int [2];
two [2] = new int [2];
Example 5:
int two [][] = new int [3][];
two [0] = new int [1];
two [1] = new int [3];
two [2] = new int [2];
(Differing-size second dimension)

© Ganapathi Nayak K
25
Arrays

Alternate methods of declaration


Alternate syntax:
1-D: type [] var-name;
2-D: type [][] var-name;
Example 1:
int a [] = new int [3];
int [] a = new int [3];
Example 2:
int b [][] = new int [3][4];
int [][] b = new int [3][4];
Example 3:
int num1 [], num2 [], num3 [];
int [] num1, num2, num3;

© Ganapathi Nayak K
26
Operators

Arithmetic and Relational Operators

Operator Result Operator Result


+ Addition == Equal to
- Subtraction (also unary minus) != Not equal to
* Multiplication > Greater than
/ Division < Less than
% Modulus >= Greater than or equal to
++ Increment <= Less than or equal to
-- Decrement
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

© Ganapathi Nayak K
27
Operators

Bitwise and Boolean Logical Operators

Operator Result Operator Result


~ Bitwise unary NOT & Logical AND
& Bitwise AND | Logical OR
| Bitwise OR ^ Logical exclusive OR
^ Bitwise exclusive OR || Short-circuit OR
>> Shift right && Short-circuit AND
>>> Shift right zero fill ! Logical unary NOT
<< Shift left &= AND assignment
&= Bitwise AND assignment |= OR assignment
|= Bitwise OR assignment ^= XOR assignment
^= Bitwise exclusive OR assignment == Equal to
>>= Shift right assignment != Not equal to
>>>= Shift right zero fill assignment ?: Ternary if-then-else
<<= Shift left assignment

© Ganapathi Nayak K
28
Operators

Assignment and Ternary Operators


Assignment operator
Syntax: var = expression;

Example: x = 10; y = 4.5; p = q = ‘a’

Ternary Operator
Syntax: expression 1 ? expression 2 : expression 3;

Example: ratio = (den == 0) ? 0 : (num / den);

© Ganapathi Nayak K
29
Operators

Operator Precedence
Highest
() [] • Note:
++ -- ~ ! 1. First row contains separators (and
* / % not operators), but they act as
operators in an expression.
+ -
>> >>> << 2. Within each row, all operators have
the same precedence.
> >= < <=
== != 3. Precedence can be changed using
parentheses.
&
|
&&
||
?:
= op=
Lowest

© Ganapathi Nayak K
30
Mathematical Functions

Math class (java.lang)

Function Meaning Function Meaning


sin(x) Sine of x log10(x) Logarithm of x base 10
cos(x) Cosine of x sqrt(x) Square root of x
tan(x) Tangent of x cbrt(x) Cube root of x
asin(x) Arc Sine of x abs(x) Absolute of x
acos(x) Arc Cosine of x max(a, b) Maximum of a and b
atan(x) Arc Tangent of x min(a, b) Minimum of a and b
atan2(x, y) Arc Tangent of x / y ceil(x) Ceiling of x
pow(x, y) x to the power y floor(x) Floor of x
exp(x) Exponential of x round(x) Rounded value of x
log(x) Natural logarithm of x

© Ganapathi Nayak K
31
Control Statements

Selection statements
The if statement
Syntax: Same as in C and C++
– if statements can be nested
– if-else-if ladder can be used

The switch statement


Syntax: Same as in C and C++
– switch statements can be nested

Note:
From JDK 7 onwards, strings can be used as case labels in ‘switch’ statement

© Ganapathi Nayak K
32
Control Statements

Iteration statements
The while statement
Syntax: Same as in C and C++

The do-while statement


Syntax: Same as in C and C++

The for statement


Syntax: Same as in C and C++

© Ganapathi Nayak K
33
Control Statements

Iteration statements (Continued …)


The for-each version of for statement (enhanced for)
Syntax: for (type itr-var : collection) statement block;
Example 1: int nums[] = {1, 2, 3, 4, 5}, sum = 0;
for (int x : nums) sum += x;
Example 2: int nums[] = {1, 2, 3, 4, 5}, sum = 0;
for (int x : nums)
{
sum += x;
if (x == 2) break;
}
Example 3: int nums[] = {1, 2, 3, 4, 5}, sum = 0;
for (int x : nums)
{
sum += x; x = x + 2; // no effect on nums
}
// collection is “read-only”

© Ganapathi Nayak K
34
Control Statements

Jump (transfer of control) statements


Basic form of the break statement
Syntax: Same as in C and C++
– Used with switch statement and loops

Labeled break statement


Syntax: break label;
Example: outerLoop: for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
{
if (j == 3) break outerLoop;
System.out.println (“In”);
}
System.out.println (“Mid”);
}
System.out.println (“Out”);

© Ganapathi Nayak K
35
Control Statements

Jump (transfer of control) statements (Continued …)


Basic form of the continue statement
Syntax: Same as in C and C++
– Used for early termination of loops

Labeled continue statement


Syntax: continue label;
Example: outerLoop: for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
{
if (j == 3) continue outerLoop;
System.out.println (“In”);
}
System.out.println (“Mid”);
}
System.out.println (“Out”);

© Ganapathi Nayak K
36
Control Statements

Jump (transfer of control) statements (Continued …)


The return statement
Syntax: Same as in C and C++
– Used to return from a method

Other jump statements (used with exception handling)


 try

 catch

 throw

 throws

 finally

© Ganapathi Nayak K
37
Class Fundamentals

Classes and Objects


Class defines a new data type; Used to create objects
Class is a template for an object; Object is an instance of class
Defining a class
class className [extends superClassName]
{
[fields declaration;]
[methods declaration;]
}
Class can be empty
No need of semicolon after closing brace

© Ganapathi Nayak K
38
Class Fundamentals

Classes and Objects (Continued …)


Members of a class
 Instance variables (fields / member variables): Data / variables defined within a class
 Methods: Contain the code
Declaring member variables
 Normal variable declaration
Declaring methods
type methodName (parameter-list)
{
method-body;
}
Constructor: As in C++
Destructor: No destructor in Java
 Uses the concept of garbage collection and finalize() method

© Ganapathi Nayak K
39
Class Fundamentals

Classes and Objects (Continued …)


Creating objects (instantiation)
Syntax
className objectName;
objectName = new className();
OR
className objectName = new className();
Example
Box myBox;
myBox = new Box();
OR
Box myBox = new Box();

© Ganapathi Nayak K
40
Class Fundamentals

Classes and Objects (Continued …)


Object Reference
 Whenwe assign one object reference variable to another object reference variable,
new copy of the object is not created, we are only making a copy of the reference
Box b1 = new Box();
Box b2 = b1;
 Reference variables b1 and b2 refer to the same object

© Ganapathi Nayak K
41
Class Fundamentals

Classes and Objects (Continued …)


Accessing class members
Syntax
objectName.variableName = value; // set
value = objectName.variableName; // get
objectName.methodName(parameter-list); // invoke a method
Example
myBox.length = 10;
myBox.getData(10, 15, 5);
myBox.volume();

© Ganapathi Nayak K
42
Class Fundamentals

Classes and Objects (Continued …)


Example
class Box {
double width, height, depth;
}
class BoxDemo {
public static void main(String args[]) {
Box myBox = new Box();
double vol;
myBox.width = 10;
myBox.height = 20;
myBox.depth = 15;
vol = myBox.width * myBox.height * myBox.depth;
System.out.println(“Volume = ” + vol);
}
}

© Ganapathi Nayak K
43
Class Fundamentals

Constructors
A method that
 Initializes an object immediately upon creation
 Has same name as class name
 Has no return type, not even void
– implicit return type is type of the class
– returns the instance of the class
 Can accept parameters (Parameterized constructors)

© Ganapathi Nayak K
44
Class Fundamentals

Constructors (Continued …)
Example
class Box {
double width, height, depth;
Box() {width = 10; height = 15; depth = 8;}
Box(double w, double h, double d)
{width = w; height = h; depth = d;}
double volume()
{ return width * height * depth; }
}
class BoxDemo {
public static void main(String args[]) {
Box myBox1 = new Box();
Box myBox2 = new Box(20, 12, 10);
System.out.println(“Volume of box 1 = ” + myBox1.volume());
System.out.println(“Volume of box 2 = ” + myBox2.volume());
}
}

© Ganapathi Nayak K
45
Class Fundamentals

The this keyword


Used inside any method to refer to the object that invoked it
Example:
Box (double w, double h, double d)
{
this.width = w; // width = w;
this.height = h; // height = h;
this.depth = d; // depth = d;
}
 Here, use of this keyword is redundant (not necessary)
 Evenwithout it, the three statements refer to the instance variables of the object that
invoked the constructor

© Ganapathi Nayak K
46
Class Fundamentals

The this keyword (Continued …)


Used for resolving any name space collisions between instance variables
and formal arguments
 Instance variable hiding: When instance variables have the same name as local
variables (including formal arguments), local variables hide the instance variables
Example
Box (double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}

© Ganapathi Nayak K
47
Class Fundamentals

Garbage Collection
C++ delete operator: dynamically allocated (using new operator) objects
manually released (recycled)
Java handles deallocation automatically using a technique called garbage
collection
 Whenno references to an object exists (that object is assumed to be no longer
needed), the memory occupied by the object is reclaimed (at random)
 Different Java run-time implementations will take varying approaches to garbage
collection

© Ganapathi Nayak K
48
Class Fundamentals

The finalize() method


Finalization is used to define specific actions to be done when an object is
about to be reclaimed by garbage collector (a part of JVM)
 Javarun-time system calls this method whenever it is about to recycle an object of
that class
 Example: Before an object is destroyed, any non-Java resources (such as file handle)
have to be released
Done using finalize() method
(protected non-static method of java.lang.Object class)
 Specify all required actions in this method
protected void finalize() throws Throwable
{ // Required code }
 Keyword protected prevents access to finalize() method by code defined outside its
class

Note: The finalize() method approximates the function of a destructor


(not supported by Java)
© Ganapathi Nayak K
49
Overloading of Methods

Method Overloading
Defining two or more methods in a class that share the same name, with
different parameter declarations
A type of Polymorphism – one interface, multiple methods
 Overloaded methods must differ in the type and/or number of parameters
 Invoking an overloaded method
– Java uses type and/or number of arguments for determining the required method
(and not the return type)
– Possibility of type promotion
In C, three versions of abs():
 abs() for integer
 fabs() for floating-point
 labs() for long integer
In Java, abs() overloaded

© Ganapathi Nayak K
50
Overloading of Methods

Method Overloading (Continued …)


Example:
class OverloadDemo {
void test() { … }
void test(int a, int b) { … }
void test(double a) { … }
}
Invoking these methods
ob.test(); // First method
ob.test(5, 10); // Second method
ob.test(50.65); // Third method
ob.test(8); // No match for integer argument 8
// promoted to double and third method invoked

Note: If the third method (and the corresponding method invocation) is not present,
we get an error for the last method invocation.

© Ganapathi Nayak K
51
Overloading of Methods

Overloading Constructors
Example:
 Constructors

Box()
{ height = 0; width = 0; depth = 0; }
Box(double h, double w, double d) // for a cuboid
{ height = h; width = w; depth = d; }
Box(double len) // for a cube
{ height = width = depth = len; }

 Invoke as
Box myBox1 = new Box();
Box myBox2 = new Box(10, 8, 6);
Box myBox3 = new Box(5);

© Ganapathi Nayak K
52
Passing Objects

Passing objects as arguments to methods


Primitive type arguments – passed by value
Objects – passed by reference
 When a variable of class type is created, we are only creating a reference to the
object
Example:
class Test In the calling function:
{
int num; Test obj = new Test();
Test() { num = 10; } int k = 10;
void meth1(int n) obj.meth1(k); // k will not change (10)
{ n += 5; } obj.meth2(obj); // obj.num changes (10 and 15)
void meth2(Test ob)
{ ob.num += 5: }
}

© Ganapathi Nayak K
53
Returning Objects

Returning objects from methods


Method can return any type of data (including objects)
Example:
class Test In the calling function:
{
int num; Test obj1 = new Test(5);
Test(int n) { num = n; } Test obj2;
Test increment() obj2 = obj1.increment(); // 5, 15
{ obj2 = obj2.increment(); // 25
Test temp = new Test(num+10);
return temp;
}
}

© Ganapathi Nayak K
54
Recursion

Recursion and recursive functions


Recursion: Process of calling a function from itself
Recursive function: A function that calls itself
Example:
class Factorial In calling function:
{
int fact (int n) Factorial f = new Factorial();
{ k = f.fact(5);
if (n == 1) return 1;
return n * fact(n-1);
}
}

© Ganapathi Nayak K
55
Access Control

Access specifiers
public : Can be accessed by any other code
» main() is declared as public
(should be accessible to Java run-time system)
private : Can be accessed by other members of its class
protected : Applies only when inheritance is used

When no access specifier is used


 Bydefault, member of a class is public within its own package (but, cannot be
accessed outside its package)

© Ganapathi Nayak K
56
Access Control

Access specifiers (Continued …)


Example:
class Test In the calling function (in another class):
{
int a; // default public int k;
public int b; Test ob = new Test();
private int c; ob.a = 10; // Valid
void setc(int i) ob.b = 15; // Valid
{ c = i; } ob.c = 20; // Error
int getc() ob.setc(20); // Through method
{ return c; } k = ob.getc()
}

© Ganapathi Nayak K
57
Access Control

Static members of a class


Can be accessed without reference to any object
 E.g., main() method (called before any objects exist)
Instance variables can be static
 Act like global variables
 When objects are created, no copy of static variables is made
 All objects share the same static variable
Methods can be static
 Can call other static methods directly
 Can access static data directly
 Can’t access instance methods and instance variables directly
 Can’t refer to this or super in any way
If computation is required to initialize static variable
 Declare a static block (gets executed only once, when the class is first loaded)

© Ganapathi Nayak K
58
Access Control

Static members of a class (Continued …)


Example:
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{ System.out.println (x + “\t” + a + “\t” + b); }
static {b = a * 4; System.out.println (“Initialized” + b);}
public static void main(String args[])
{ meth(42); }
}
 As soon as UseStatic class is loaded, all the static statements are executed
 Output: Initialized 12
42 3 12

© Ganapathi Nayak K
59
Access Control

Static members of a class (Continued …)


Can be used outside the class in which they are defined
 Without using any object
 Specify name of the class followed by dot operator
Example:
class StaticDemo {
static int a = 42, 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);
}
}

© Ganapathi Nayak K
60
Access Control

final variable
Prevents the contents of the variable being modified
 Should be initialized when it is declared
 Variable is essentially a constant
 Do not occupy memory on per-instance basis
 Coding convention used: All uppercase identifiers
 Can be initialized within a constructor (instance variable)
 Examples:
final double INTEREST_RATE = 10
final int FILE_NEW = 1

Can also be applied to methods (cannot be inherited)

© Ganapathi Nayak K
61
Array as an Object

length instance variable


An array is implemented as an object
 Instance variable length: Size of the array
– Number of elements that an array can hold
– Not number of elements actually used

Example:
class Length{
public static void main(String args[]) {
int a1[] = new int [10];
int a2[] = { 1, 2, 3, 4, 5 };
System.out.println (a1.length); // 10
System.out.println (a2.length); // 5
}
}

© Ganapathi Nayak K
62
Nested and Inner Classes

Nested Classes
Scope of a nested class is bounded by the scope of the enclosing class
 Example: If B is defined within A, B does not exist independently of A

Nested class can access all members (including private) of the class in
which it is nested

The enclosing class cannot access members of nested class

Possible to declare a nested class that is local to a block

© Ganapathi Nayak K
63
Nested and Inner Classes

Nested Classes (Continued …)

2 types of nested classes

 Static:

– A class that has static modifier applied

– Can access only static members of the enclosing class

– Cannot directly access non-static members of its enclosing class

» It must access members of its enclosing class through an object

 Non-static (Inner):

– Has access to all variables and methods of its outer class

– Can refer to them directly (similar to non-static members of the outer class)

© Ganapathi Nayak K
64
Nested and Inner Classes

Nested Classes (Continued …)


Example:
class Outer class InnerClassDemo {
{ public static void main(String args[])
int outer_x = 100; {
void test Outer outer = new Outer();
{ outer.test();
Inner inner = new Inner(); }
inner.display(); }
} // Output: 100
class Inner
{
void display()
{
System.out.println(outer_x);
}
}
}

© Ganapathi Nayak K
65
Nested and Inner Classes

Nested Classes (Continued …)


Important points:
 Instance of the inner class can be created only within the scope of the outer class
 Compiler error if any code outside the class Outer attempts to instantiate class Inner
 But,
we can create an instance of Inner class outside the Outer class by qualifying its
name with Outer and using an Outer object as follows:
Outer . Inner inner = outer . new Inner();
inner . display();
 Aninner class has access to all members of its enclosing class, but, reverse is not true
(members of inner class are known only within the scope of inner class)
 It is possible to declare inner classes within any block scope

© Ganapathi Nayak K
66
Nested and Inner Classes

Nested Classes (Continued …)


Example:
class Outer
{
int outer_x = 100;
class Inner
{
int y = 10; // Cannot be used outside the class Inner
void display()
{ System.out.println(outer_x); }
}
void show_y()
{ System.out.println(y); } // Error
}

© Ganapathi Nayak K
67
Nested and Inner Classes

Nested Classes (Continued …)


Example for inner class within a block:
void test()
{
for(int i=0; i<10; i++)
{
class Inner
{
void display()
{ System.out.println(outer_x); }
}
Inner inner = new Inner();
inner.display();
}
}

Output: 100 displayed 10 times

© Ganapathi Nayak K
68
Command Line Arguments

Command Line Arguments


Pass information into a program on invoking it
Accessed using String array argument of main()
 args[0], args[1], …
All arguments are passed as strings
 Conversion to other types should be done in the program
Example:
class CommandLine {
public static void main(String args[]) {
(for int i = 0; i < args.length; i++)
System.out.println(“args[” + i + “] = ” + args[i]);
}
}
Run this as: java CommandLine Java 100 -5
Output: args[0] = Java
args[1] = 100
args[2] = -5

© Ganapathi Nayak K
69
String Handling

String Class
A string is an object of type String
Defined in the package java.lang as ‘final’ (cannot be inherited)
Not an array of characters
 Not terminated by NULL
Objects are immutable (cannot be altered)
 Fixed length
Two peer classes StringBuffer and StringBuilder
 Hold strings that can be modified after they are created
+ operator can be used for concatenating two or more strings
String s = “MIT” + “Manipal”;
System.out.println(“Value is ” + value);

© Ganapathi Nayak K
70
String Handling

String Class (Continued …)


Constructors:
String ()
String s1 = new String (); // Empty string
String (char charArray[])
String (char charArray[], int startIndex, int numChars)
char ch[] = {‘a’, ‘b’, ‘c’ , ‘d’, ‘e’, ‘f’ };
String s2 = new String (ch); // “abcdef”
String s3 = new String (ch, 2, 3); // ”cde”

© Ganapathi Nayak K
71
String Handling

String Class (Continued …)


Constructors:
String (String strObj)
String s4 = new String (s3) // “cde”
String (byte charArray[])
String (byte charArray[], int startIndex, int numChars)
byte asc[] = { 65, 66, 67, 68, 69, 70);
String s5 = new String (asc); // ”ABCDEF”
String s6 = new String (asc,2,3); // “CDE”

Note: We can also create a string without using a constructor by directly assigning a value to it.
Example: String s7 = “Manipal”;

© Ganapathi Nayak K
72
String Handling

String Class (Continued …)


String methods (Character Extraction):

char charAt (int index)

void getChars (int sourceStart, int sourceEnd, char target [], int targetStart)

byte [ ] getBytes ()

char [ ] toCharArray ()

String methods (Case conversion):

String toLowerCase ()

String toUpperCase ()

© Ganapathi Nayak K
73
String Handling

String Class (Continued …)


String methods (String comparison):

int compareTo (stringObject ob)

int compareTo (String str)

int compareToIgnoreCase (String str)

boolean startsWith (String str)

boolean startsWith (String str, int startIndex)

boolean endsWith (String str)

© Ganapathi Nayak K
74
String Handling

String Class (Continued …)


String methods (String comparison):

boolean equals (stringObject ob)

boolean equalsIgnoreCase (String str)

boolean regionMatches (int startIndex, String str2, int str2StartIndex, int numChars)
boolean regionMatches (boolean ignoreCase, int startIndex,
String str2, int str2StartIndex, int numChars)
String [ ] split ( String regex, int limit )

Note: The “equals()” method compares the characters within the strings.
The “==” operator compares two object references to see whether
they refer to the same instance.

© Ganapathi Nayak K
75
String Handling

String Class (Continued …)


String methods (Searching in a strings):

int indexOf (char ch)

int indexOf (char ch, int fromIndex)

int indexOf (String str)

int indexOf (String str, int fromIndex)

int lastIndexOf (char ch)

int lastIndexOf (char ch, int fromIndex)

int lastIndexOf (String str)

int lastIndexOf (String str, int fromIndex)

boolean contains (CharSequence str)

© Ganapathi Nayak K
76
String Handling

String Class (Continued …)


String methods (Modifying a String):

String substring (int beginIndex)

String substring (int beginIndex, int endIndex)

String concat (String str)

String replace (char oldChar, char newChar)

String replace(CharSequence original, CharSequence replacement)

String trim()

© Ganapathi Nayak K
77
String Handling

String Class (Continued …)


String methods (Data Conversion):

int length ()

boolean isEmpty ()

String toString ()

String valueOf (double num)

String valueOf (long num)

String valueOf (Object ob)

String valueOf (char chars[ ])

Note: The “valueOf()” method is a static method.

© Ganapathi Nayak K
78
String Handling

String Class (Continued …)


String methods (Data Conversion):
public class StringExample {
public static void main(String[] args) {
Object obj = "Hello World!";
System.out.println ("String.valueOf(): " + String.valueOf(obj));
System.out.println ("toString(): " + obj.toString());
obj = null;
System.out.println ("String.valueOf(): " + String.valueOf(obj));
System.out.println ("toString(): " + obj.toString());
}
}
Output: String.valueOf(): Hello World!
toString(): Hello World!
String.valueOf(): null
Exception in thread "main" java.lang.NullPointerException
at StringExample.main(StringExample.java:8)

© Ganapathi Nayak K
79
String Handling

String Class (Continued …)


String methods (Others):
class Box {
double width; double height; double depth;
Box(double w, double h, double d)
{ width = w; height = h; depth = d; }
public String toString()
{ return "Dimensions are " + width + " by " + depth + " by " + height + "."; }
}
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}

© Ganapathi Nayak K
80
String Handling

String Class (Continued …)


Creating format string:
Use String’s static format() method
Example:
String fs;
int intVar = 23;
float floatVar = 5.25f;
String stringVar = “Computer Applications”;
fs = String.format (”Values are %d %f %s“, intVar, floatVar, stringVar);
System.out.println (fs);
// System.out.format (”Values are %d %f %s“, intVar, floatVar, stringVar);

Output: Values are 23 5.250000 Computer Applications

© Ganapathi Nayak K
81
String Handling

StringBuffer Class
Strings that can be altered both in terms of length and content
StringBuffer constructors:

StringBuffer ()

StringBuffer (int capacity)

StringBuffer (String str)

StringBuffer (CharSequence chars)

© Ganapathi Nayak K
82
String Handling

StringBuffer Class (Continued …)


StringBuffer Methods:

int capacity ()

int length ()

char charAt (int index)

int indexOf (String str)

int indexOf (String str, int fromIndex)

int lastIndexOf (String str)

int lastIndexOf (String str, int fromIndex)

StringBuffer reverse()

© Ganapathi Nayak K
83
String Handling

StringBuffer Class (Continued …)


StringBuffer Methods:

void setCharAt (int index, char ch)

void setLength (int newLength)

String substring (int start)

String substring (int start, int end)

String toString()

void trimToSize()

StringBuffer delete (int start, int end)

StringBuffer deleteCharAt (int index)

© Ganapathi Nayak K
84
String Handling

StringBuffer Class (Continued …)


StringBuffer Methods:

StringBuffer append (arg)

StringBuffer append (char[] str, int offset, int len)

StringBuffer insert (int offset, arg)

StringBuffer insert (int index, char[] str, int offset, int len)

StringBuffer replace (int start, int end, String str)

arg = boolean, char, char[], double, float, int, long, String, StringBuffer

© Ganapathi Nayak K
85
Wrapper Classes

Wrapper Classes
Contained in java.lang package
Used for wrapping primitive data into objects and vice versa
Immutable – a primitive data in stored in an object, cannot be modified

Simple Type Wrapper Class

boolean Boolean

char Character

double Double

float Float

int Integer

long Long

byte Byte

short Short

© Ganapathi Nayak K
86
Wrapper Classes

Wrapper Classes (Continued …)


Methods for converting primitive numbers to object numbers (using
constructor methods)

Method called Conversion from Conversion to

Integer intObj = new Integer(int) Primitive int Integer object

Float floatObj = new Float(float) Primitive float Float object

Double doubleObj = new Double(double) Primitive double Double object

Long longObj = new Long(long) Primitive long Long object

Character charObj = new Character(char) Primitive char Character object

Byte byteObj = new Byte(byte) Primitive byte Byte object

Short shortObj = new Short(short) Primitive short Short object

Boolean booleanObj = new Boolean(boolean) Primitive boolean Boolean object

© Ganapathi Nayak K
87
Wrapper Classes

Wrapper Classes (Continued …)


Methods for converting object numbers to primitive numbers (using
typeValue() methods)

Method called Conversion from Conversion to

int intVal = intObj.intValue() Integer Object Primitive integer

float floatVal = floatObj.floatValue() Float Object Primitive float

long longVal = longObj.longValue() Long Object Primitive long

double doubleVal = doubleObj.doubleValue() Double Object Primitive double

byte byteVal = byteObj.byteValue() Byte Object Primitive byte

short shortVal = shortObj.shortValue() Short Object Primitive short

© Ganapathi Nayak K
88
Wrapper Classes

Wrapper Classes (Continued …)


Methods for converting primitive numbers to string objects (using toString()
method)

Method called Conversion from Conversion to

String strVal = Integer.toString(int) Primitive integer String

String strVal = Float.toString(float) Primitive float String

String strVal = Double.toString(double) Primitive double String

String strVal = Long.toString(long) Primitive long String

String strVal = Short.toString(short) Primitive short String

String strVal = Byte.toString(byte) Primitive byte String

© Ganapathi Nayak K
89
Wrapper Classes

Wrapper Classes (Continued …)


Methods for converting string objects to numeric objects (using valueOf()
method)

Method called Conversion from Conversion to

int intVal = Integer.valueOf(String) String Integer object

float floatVal = Float.valueOf(String) String Float object

long longVal = Long.valueOf(String) String Long object

double doubleVal = Double.valueOf(String) String Double object

short shortVal = Short.valueOf(String) String Short object

byte byteVal = Byte.valueOf(String) String Byte object

boolean booleanVal = Boolean.valueOf(String) String Boolean object

© Ganapathi Nayak K
90
Wrapper Classes

Wrapper Classes (Continued …)


Methods for converting numeric strings to primitive numbers (using parsing
method)

Method called Conversion from Conversion to

int intVal = Integer.parseInt(String) String Primitive integer

long longVal = Long.parseLong(String) String Primitive long

float floatVal = Float.parseFloat(String) String Primitive float

double doubleVal = Double.parseDouble(String) String Primitive double

byte byteVal = Byte.parseByte(String) String Primitive byte

short shortVal = Short.parseShort(String) String Primitive short

boolean booleanVal = Boolean.parseBoolean(String) String Primitive boolean

© Ganapathi Nayak K
91
Autoboxing and Unboxing

Autoboxing
Automatic conversion of primitive type into corresponding wrapper class
object (boxed into wrapper class)
 Occurs when an object is expected and primitive type is available
 Uses valueOf() method to convert primitive to Object
Examples:
1. Integer iObject = 3;
2. public static void show (Integer iParam)
{
System.out.println (iParam);
}
In calling method:
show(3);

© Ganapathi Nayak K
92
Autoboxing and Unboxing

Unboxing
Automatic conversion of object into corresponding primitive type (unboxed
from wrapper class)
 Occurs when an primitive type is expected and object is available
 Uses intValue(), doubleValue() etc. to get primitive value from Object
Examples:
1. int n = iObject;
2. public static Integer show (Integer iParam)
{
System.out.println (iParam);
return iParam;
}
In calling method:
int result = show(3);

© Ganapathi Nayak K
93
Variable-Length Arguments

Varargs
New technique introduced in JDK 5
Earlier techniques:
 Ifthe maximum number of arguments is small and known, create overloaded versions
of the method one for each way the method could be handled
– Example 1
 Ifthe maximum number of arguments is large and unknown, put the arguments in an
array and pass the array to the method
– Example 2

© Ganapathi Nayak K
94
Variable-Length Arguments

Varargs (Continued …)
Example 1:
class OverLoad {
static void vaTest () { }
static void vaTest (int a) { }
static void vaTest (int a, int b) { }

public static void main(String args[]) {


vaTest (); // no args
vaTest (10); // 1 args
vaTest (15, 18); // 2 args
}
}

© Ganapathi Nayak K
95
Variable-Length Arguments

Varargs (Continued …)
Example 2:
class PassArray {
static void vaTest (int v[]) {
System.out.print ("Number of args: " + v.length + “\nContents: ");
for (int x : v) System.out.print (x + " ");
System.out.println ();
}

public static void main(String args[]) {


int n0[] = { };
int n1[] = { 10 };
int n2[] = { 15, 18 };
vaTest (n0); // no args
vaTest (n1); // 1 arg
vaTest (n2); // 2 args
}
}

© Ganapathi Nayak K
96
Variable-Length Arguments

Varargs (Continued …)
A variable-length argument is specified by three dots (…)
class VarArgs {
static void vaTest (int … v) {
System.out.print("Number of args: " + v.length + “\nContents: ");
for(int x : v) System.out.print (x + " ");
System.out.println();
}

public static void main(String args[]) {


vaTest (); // no args
vaTest (10); // 1 arg
vaTest (15, 18); // 2 args
}
}

© Ganapathi Nayak K
97
Variable-Length Arguments

Varargs (Continued …)
Normal parameters can be used with variable-length arguments
 Normal parameters should precede variable-length arguments
There must be only one variable-length parameter

Examples:
void vaTest (int a, float b, char c, int … vals); // valid
void vaTest (int a, int … vals, float b, char c); // invalid
void vaTest (int a, int … v1, double … v2); // invalid

© Ganapathi Nayak K
98
Variable-Length Arguments

Varargs (Continued …)
Varargs methods can be overloaded
class VarArgs {
static void vaTest (int ... v) { }
static void vaTest (boolean ... v) { }
static void vaTest (double ... v) { }

public static void main(String args[])


{
vaTest (1, 2, 3);
vaTest (true, false, false);
vaTest (12.75, 17.45, -34.6, 23.91);
}
}

© Ganapathi Nayak K
99
Variable-Length Arguments

Varargs (Continued …)
Overloaded Varargs methods can lead to ambiguity
Case 1:
class VarArgs {
static void vaTest (int ... v) { }
static void vaTest (boolean ... v) { }

public static void main(String args[])


{
vaTest (1, 2, 3);
vaTest (true, false, false);
vaTest (); // ambiguous
}
}
Since the vararg parameter can be empty, the last call can be translated into a call to
either of the two methods

© Ganapathi Nayak K
100
Variable-Length Arguments

Varargs (Continued …)
Overloaded Varargs methods can lead to ambiguity
Case 2:
class VarArgs {
static void vaTest (int ... v) { }
static void vaTest (int) { }

public static void main(String args[])


{
vaTest (1); // ambiguous
}
}
Compiler cannot resolve the issue of whether to translate the method call into first
method or the second

© Ganapathi Nayak K
101
Inheritance

Meaning of inheritance
Mechanism in which one object acquires properties of another object
Create new classes that are built upon existing (parent) class
Methods and fields of parent class can be reused
New methods and fields can be added

© Ganapathi Nayak K
102
Inheritance

Superclass and Subclass


Create subclass from superclass
 Subclassinherits all (except private) instance variables and methods (except
constructors) of super class and adds its own unique instance variables and methods
 Subclass cannot access private members of superclass (they are not inherited into the
subclass)
 Private members of a superclass are accessible by methods of superclass only
Syntax:
class subclass-name extends superclass-name
{
// body of class
}
 Only one superclass for any subclass (multiple inheritance not supported)
 Hierarchy of inheritance can be used (multilevel inheritance)

© Ganapathi Nayak K
103
Inheritance

Superclass and Subclass (Continued …)


Example

class A { class SimpleInheritance {


int i, j; public static void main(String args[]) {
void showij () { A superOb = new A();
System.out.println (i + “ ” + j); B subOb = new B();
} superOb.i = 10;
} superOb.j = 20;
class B extends A { superOb.showij(); // 10 20
int k; subOb.i = 30;
void showk () { subOb.j = 40;
System.out.println (k); subOb.k = 50;
} subOb.showij(); // 30 40
} subOb.showk(); // 50
}
}
© Ganapathi Nayak K
104
Inheritance

Keyword super
Used in a subclass to refer to its immediate superclass
Form 1 (Example 1)
 To call superclass constructors
 Super must always be the first statement inside a subclass’ constructor
 Syntax: super(arg-list);
Form 2 (Example 2)
 To access members of superclass hidden by subclass
 Syntax: super.member
 Member can be either a method or an instance variable

© Ganapathi Nayak K
105
Inheritance

Keyword super (Continued …)


Example 1
class Box {
double width, height, depth;
Box (double w, double h, double d)
{ width = w; height = h; depth = d; }
}
class BoxWeight extends Box {
double weight;
BoxWeight (double w, double h, double d, double wt)
{ super(w, h, d); weight = wt; }
}
In main(): BoxWeight box = new BoxWeight (10, 20, 15, 2.5);

© Ganapathi Nayak K
106
Inheritance

Keyword super (Continued …)


Example 2
class A {
int m;
}
class B extends A {
int m; // This m hides m in A
B (int a, int b) { super.m = a; m = b; }
void show() {
System.out.println (“m in superclass A = “ + super.m);
System.out.println (“m in subclass B = “ + m);
}
}
In main(): B subOb = new B (10, 20);
subOb.show ();

© Ganapathi Nayak K
107
Inheritance

Keyword super (Continued …)


super in a subclass refers to its immediate superclass
 Constructors
are called in the order of derivation, from superclass to subclass,
whether or not super() is used
– If super() is used, it must be the first statement in a subclass’ constructor
– If super() is not used, the no-argument constructor of each class is executed

© Ganapathi Nayak K
108
Inheritance

Multilevel hierarchy
Multiple levels of inheritance
 Class A → Class B → Class C …
Example:
class A {
// Body of class A
}
class B extends A {
// Body of class B
}
class C extends B {
// Body of class C
}

© Ganapathi Nayak K
109
Inheritance

Multilevel hierarchy (Continued …)


Example:
class A {
A() { System.out.println (“Inside A’s constructor”); }
}
class B extends A {
B() { System.out.println (“Inside B’s constructor”); }
}
class C extends B {
C() { System.out.println (“Inside C’s constructor”); }
}
In main(): C objC = new C();
Output: Inside A’s constructor
Inside B’s constructor
Inside C’s constructor

© Ganapathi Nayak K
110
Inheritance

Method overriding
When a subclass method has same name as a superclass method
 If type of signatures (number and data type) are same (Example 1)
– Method in the subclass overrides the method in superclass
– When called, subclass method is used (superclass method is hidden)
 If type of signatures (number and data type) are not same (Example 2)
– Two methods are overloaded

© Ganapathi Nayak K
111
Inheritance

Method overriding (Continued …)


Example 1
class A {
void show (int n) { System.out.println (“In A: ” + n); }
}
class B extends A {
void show (int n) { System.out.println (“In B: ” + n); }
}
class Override {
public static void main (String args[]) {
B subOb = new B();
subOb.show (10); // this calls show() in B
}
}

Output: In B: 10

© Ganapathi Nayak K
112
Inheritance

Method overriding (Continued …)


Example 1 (Modified)
class A {
void show (int n) { System.out.println (“In A: " + n); }
}
class B extends A {
void show (int n) { super.show(n); System.out.println(“In B: " + n); }
}
class Override {
public static void main (String args[]) {
B subOb = new B();
subOb.show (10); // this calls show() in B
}
}

Output: In A: 10
In B: 10

© Ganapathi Nayak K
113
Inheritance

Method overriding (Continued …)


Example 2
class A {
void show (int n) { System.out.println (“In A: ”+ n); }
}
class B extends A {
void show (String s) { System.out.println (“In B: ” + s); }
}
class Overload {
public static void main(String args[]) {
B subOb = new B();
subOb.show (10); // this calls show() in A
subOb.show (“MCA”); // this calls show() in B
}
}

Output: In A: 10
In B: MCA

© Ganapathi Nayak K
114
Inheritance

Dynamic Method Dispatch


Mechanism by which a call to overridden method is resolved at run time,
rather than at compile time
 Basis for run-time polymorphism
Principle used: A superclass reference variable can refer to a subclass
object
 When a overridden method is called through a superclass reference, Java determines
which version of that method to execute at that time
 Decisionis made based on the type of the object being referred to and not on the
type the reference variable
Upcasting: Reference variable of superclass referring to object of subclass
 Example:

class A { }
class B extends A { }
In main(): A obj = new B(); // upcasting

© Ganapathi Nayak K
115
Inheritance

Dynamic Method Dispatch (Continued …)


Example 1:
class A { In main():
void callMe() {
System.out.println ("A's callMe"); A aObj = new A();
} B bObj = new B();
} C cObj = new C();
class B extends A {
void callMe() { // reference variable for A
System.out.println ("B's callMe"); A refVar;
}
} refVar = aObj; refVar.callMe(); //A
class C extends A { refVar = bObj; refVar.callMe(); //B
void callMe() { refVar = cObj; refVar.callMe(); //C
System.out.println ("C's callMe");
}
}

© Ganapathi Nayak K
116
Inheritance

Dynamic Method Dispatch (Continued …)


Example 2:
class Bank { class Bank1 extends Bank {
int getRate() {return 0;} int getRate() {return 8;}
} }

class Bank2 extends Bank {


int getRate() {return 7;}
}

class BankTest {
public static void main(String args[]) {
Bank b1=new Bank1();
Bank b2=new Bank2();
System.out.println (“Rate of interest”);
System.out.println (“Bank 1: "+ b1.getRate());
System.out.println (“Bank 2: "+ b2.getRate());
}
}
© Ganapathi Nayak K
117
Inheritance

Use of overridden methods


Polymorphism (one interface, multiple methods)
 Allows a general class to specify methods that will be common to all its subclasses
 Allows subclasses to define specific implementations of some or all these methods
3 methods to implement polymorphism
 Method overloading
 Method overriding
 Interfaces

© Ganapathi Nayak K
118
Inheritance

Abstract classes
Abstract class is a class that cannot be instantiated
Superclass declares the structure of a given abstraction without providing a
complete implementation of every method
 Definesa generalized form that will be shared by all its subclasses, leaving it to each
subclass to fill in the details

To specify that certain methods must be overridden by subclasses, specify


abstract type modifier with superclass
 No implementation in superclass
 Subclass’ responsibility to implement them
 Syntax of declaring an abstract method:
abstract type name (parameter-list);

© Ganapathi Nayak K
119
Inheritance

Abstract classes (Continued …)


Any class that contains one or more abstract methods must be declared
abstract
 use abstract keyword before the keyword class
Cannot create objects of abstract class
 Because such objects are of no use
Cannot declare abstract constructors
Cannot have abstract static methods
Any subclass of an abstract class must
 Either implement all abstract methods specified in the superclass
 Or be itself an abstract class

Note: A non-abstract class is called a concrete class

© Ganapathi Nayak K
120
Inheritance

Abstract classes (Continued …)


Example:
abstract class A {
abstract void callMe ();
void callMeToo () { System.out.println (“Class A: callMeToo()”); }
}
class B extends A {
void callMe () { System.out.println (“Class B: callMe()”); }
}
class AbstractDemo {
public static void main (String args[]) {
B b = new B();
b.callMe();
b.callMeToo();
}
}
Output: Class B: callMe()
Class A: callMeToo()

© Ganapathi Nayak K
121
Inheritance

Run-time polymorphism
Not possible to instantiate objects of Abstract classes; but, object
references can be created
Run-time polymorphism implemented through the use of superclass
references
Possible to create a reference to an abstract class so that it can be used to
point to a subclass object

Example: Polymorphism in Figure class

© Ganapathi Nayak K
122
Inheritance

Using final with inheritance


Prevent Overriding
 To
prevent a method from overriding, specify final as a modifier at the start of its
declaration
 Example:

class A {
final void meth() {
System.out.println ("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println ("Illegal");
}
}

© Ganapathi Nayak K
123
Inheritance

Using final with inheritance (Continued …)


Prevent Inheritance
 To
prevent a class from being overriding, specify final as a modifier at the start of its
declaration
– Declaring a class as final implicitly declares all its methods as final
 Example:

final class A {
//…
}
class B extends A { // ERROR: Cannot inherit from final A
//…
}

© Ganapathi Nayak K
124
Inheritance

Using final with inheritance (Continued …)


Advantages:
 Compiler is free to “inline” calls to final methods, because it knows that they will not
be overridden
 Bytecode of small final methods are copied directly inline with compiled code
(eliminates costly overhead of method call)
– Concept of early binding
 Java calls other methods dynamically (at run time)
– Concept of late binding

© Ganapathi Nayak K
125
Packages

What is a package ?
Container for classes
Classes with same name – possible in different packages
Classes in a package can be imported into required programs
Both a naming and visibility control mechanism
 We can define classes inside a package that are not accessible outside that package
 Wecan also define class members that are only exposed to other members of the
same package

© Ganapathi Nayak K
126
Packages

Defining a package
Include package statement as the first one in a Java source file
 Any class declared within that file belongs to that package
Package statement defines a name space in which classes are stored
 Absence of package statement puts class names in default package (without any
name)
Usage:
 Syntax: package package-name;
 Example: package myPackage;
 Storing
a package: Store the package in a folder with the same name as package
name (case is significant)

© Ganapathi Nayak K
127
Packages

Defining a package (Continued …)


More than one file can include the same package statement
 Store all classes in all these files in the same folder
Possible to create hierarchy of packages
 Separate each package name from the one above it using a period (.)
 Syntax: package pkg1[.pkg2[.pkg3]];
 Example: package java.awt.image; (store in folder java\awt\image)

© Ganapathi Nayak K
128
Packages

Defining a package (Continued …)


Example 1: (Two classes in one file AccountBalance.java)

package mypack;

class Balance {
String name; double bal;
Balance(String n, double b) { name = n; bal = b; }
void show() { System.out.println (name + " " + bal); }
}

class AccountBalance {
public static void main(String args[]) {
Balance current = new Balance ("Herbert Schildt", 1243.78);
current.show();
}
}

© Ganapathi Nayak K
129
Packages

Defining a package (Continued …)


Example 2: (Two classes in two files Balance.java and AccountBalance.java)

package mypack; // In mypack folder


public class Balance {
String name; double bal;
public Balance(String n, double b) { name = n; bal = b; }
public void show() { System.out.println (name + " " + bal); }
}

import mypack.*;
class AccountBalance { // In the parent folder of mypack
public static void main(String args[]) {
Balance current = new Balance ("Herbert Schildt", 1243.78);
current.show();
}
}

© Ganapathi Nayak K
130
Packages

Finding packages and CLASSPATH


To search for packages, three options
1. Java run-time system uses current working directory as its starting point for search
2. We can specify a directory path or paths by setting CLASSPATH environmental
variable
3. We can use –classpath option with javac and java to specify path to the classes
Example:
 set CLASSPATH=C:\MyPrograms\Java (if the required class is present in this folder)
 javac –classpath C:\MyPrograms\Java sample.java
 java –classpath C:\MyPrograms\Java sample

© Ganapathi Nayak K
131
Packages

Access Protection
Java provides four categories of visibility for class members
 Subclasses in the same package
 Non-subclasses in the same package
 Subclasses in different packages
 Classes that are neither in the same package nor subclasses
Access specifiers used
 public: can be accessed anywhere
 private: can’t be seen outside of its class
 protected: can be seen outside the current package only to direct subclasses of that
class
 (default
(package-private): visible to subclasses as well as other classes in the same
package)

Note: When a class is public, it must be the only public class in the file and the file
must have the same name as the class

© Ganapathi Nayak K
132
Packages

Access Protection (Continued …)

No
Private Protected Public
Modifier

Same class Yes Yes Yes Yes

Same package subclass No Yes Yes Yes

Same package non-subclass No Yes Yes Yes

Different package subclass No No Yes Yes

Different package non-subclass No No No Yes

© Ganapathi Nayak K
133
Packages

Importing Packages
A class from another package can be accessed using 2 methods
 By specifying the fully qualified class name
 Using import statement
The import statement is used immediately after package statement (if it
exists) and before any class definitions
 Syntax: import pkg1[.pkg2].(classname|*);
 Examples: import java.util.Date;
import java.lang.*; // basic language functions (default)
Fully qualified class name
import java.util.*;
class myDate extends Date { …}
OR
class myDate extends java.util.Date { … }

© Ganapathi Nayak K
134
Interfaces

Meaning of Interface
Java does not support multiple inheritance
 class A extends B extends C { …} is not permitted
Interface: A kind of class – with the following differences from a class
 Defines only abstract methods and final fields.
 Does not specify any code to implement these methods
 Data fields contain only constants.
 Itis the responsibility of the class that implements an interface to define the code for
implementing these methods.
Syntax:
interface InterfaceName
{
variables declaration;
methods declaration;
}
Designed to support dynamic method resolution at run time

© Ganapathi Nayak K
135
Interfaces

Implementing an Interface
Syntax:
class classname extends superclass implements interface[,interface…] {
// class body
}

Rules:
 Methods that implement an interface must be declared public
 Typesignatures of the implementing method must match exactly the type signature
specified in the interface definition

© Ganapathi Nayak K
136
Interfaces

Implementing an Interface (Continued)


Example:
interface Area { class InterfaceTest {
static final float pi=3.14F; public static void main(String args[]) {
float compute (float x, float y);
Rectangle rec = new Rectangle();
}
Circle cir = new Circle();

class Rectangle implements Area { Area ar; // interface object reference


public float compute (float x, float y) ar = rec; // ar refers to rec object
{ return x * y; } System.out.println (“Area of rectangle: ” +
} ar.compute(20, 10));
ar = cir; // ar refers to rec object
class Circle implements Area {
public float compute (float x, float y) System.out.println (“Area of circle: ” +
{ return pi * x * x; } ar.compute(20, 10));
}
}

© Ganapathi Nayak K
137
Interfaces

Extending Interfaces
Syntax:
interface name2 extends name1
{
// body of name2
}

© Ganapathi Nayak K
138
Interfaces

Extending Interfaces (Continued …)


Example 1
interface ItemConstants
{
int code = 1001;
String name = “AC”;
}
interface Item extends ItemConstants
{
void display();
}

© Ganapathi Nayak K
139
Interfaces

Extending Interfaces (Continued …)


Example 2
interface ItemConstants
{
int code = 1001;
Stringname = “AC”;
}
interface ItemMethods extends ItemConstants
{
void display();
}
interface Item extends ItemConstants, ItemMethods
{
// …
}

© Ganapathi Nayak K
140
The End

© Ganapathi Nayak K
141

You might also like