Java
Java
Java
Programming paradigms
There are different types of programming languages, such as:
Procedural Programming: is a list of instructions telling a computer,
step-by-step, what to do, usually having a linear order of execution from
the first statement to the second and so forth with occasional loops and
branches. Procedural programming language includes C, FORTRAN,
Pascal, and Basic.
Procedural languages are characterized by sequential sets of linear
commands. The focus of such languages is on structure.
Object oriented programming: allow the programmer to break down the
problem into objects: self-contained entities consisting of both data and
operations on the data. E.g. java, C#, VB.NET
•The focus of OOP languages is not on structure, but on modeling data.
Object means a real word entity such as pen, chair, table etc.
Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software development
and maintenance by providing some core concepts:
Class
Object
Encapsulation
Inheritance
Abstraction
Polymorphism
CLASS OBJECT
Class is a data type Object is an instance of Class.
It generates OBJECTS It gives life to CLASS
Does not occupy memory It occupies memory location.
location
It cannot be manipulated because it is not It can be manipulated.
available in memory (except static class)
Abstraction refers to the way in which a class represents only the essential
features of the set of objects it models – a class does not include
background or extra details that are not relevant to the system.
So a class is like a list of abstract attributes e.g. size, weight, cost, and the
methods that operate on those attributes e.g. change the cost, increase the
weight.
Hiding internal details and showing functionality is known as
abstraction. For example: phone call, we don't know the internal
processing.
Is the process of removing characteristics from something in order to
reduce it to a set of essential characteristics.
1.4 Inheritance
Inheritance is the way in which objects of one class get the properties of
objects of another class. This includes the data and the methods.
For example, take a system in which there are various types of 'person'
objects – they have some attributes in common, such as Name, Address
and Date of Birth. The person that is an Employee is part of the class
'Person', but has some extra attributes such as Salary, Department and Rank.
On the surface, inheritance is a code re-use issue. we can extend code
that is already written in a manageable manner.
Benefits of Inheritance
Used to avoid redundancy.
Useful for easy modification (modification can be made only
once)
New classes can be easily added (sometimes may require
restructuring)
Used to generalize/specialize classes
1.4. Polymorphism
The word polymorphism means the ability to take more than one
form. In terms of the OOP, this means that a particular operation may
behave differently for different sub-classes of the same class.
Consider a class hierarchy for different shapes. A Shape class
encapsulates the common features of shapes – such as drawing a
shape and calculating the area of a shape (or, in other words, each
Shape object can draw itself and can calculate its area).
Deals with the ability of an object to be of different forms.
Polymorphism comes in the form that a reference in an OO program
can refer to objects of different types at different times
1.5. Java Technology
What is Java Technology?
The Java technology is:
A programming language
A development environment
An application environment
A deployment environment
A programming language
o As a programming language, Java can create all kinds of
applications that you could create using any conventional
programming language.
A Development Environment
o As a development environment, Java technology provides you
with a large suite of tools:
A compiler (javac)
An interpreter (java)
A documentation generator (javadoc)
A class file packaging tool and so on...
An Application and Runtime Environment
Java technology applications are typically general-purpose
programs that run on any machine where the Java runtime
environment (JRE) is installed.
Deployment Environment
The JRE supplied by the Java 2 Software Development Kit
(SDK) contains the complete set of class files for all the Java
technology packages, which includes basic language classes,
GUI component classes, and so on.
By convention, all class names in Java begin with a capital letter and
capitalize the first letter of each word they include (e.g.,
SampleClassName).
A Java class name is an identifier—a series of characters consisting of
letters, digits, underscores ( _ ) and dollar signs ($) that does not begin
with a digit and does not contain spaces.
Cannot contain Java Reserved keywords
Java Reserved Keywords:
The following list shows the reserved words in Java. These reserved words
may not be used as constant or variable or any other identifier names.
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch Synchronized this throw throws
transient Try void volatile while
String literals in Java are specified like they are in most other languages
by enclosing a sequence of characters between a pair of double quotes.
Examples of string literals are:
"Hello
World"
"two\n
lines"
"\"This is in quotes\""
Variables
A variable provides us with named storage that our programs can
manipulate. Each variable in Java has a specific type, which determines
the size and layout of the variable's memory; the range of values that can
be stored within that memory; and the set of operations that can be
applied to the variable.
Three types of Variables in Java
Local variables
Declared in methods and includes method parameter
Not accessible outside the methods and don’t get default value.
Instance variables
Declared within the class and Represent Object State
Gets default value and cannot be reinitialized within the class
Class variables (Static Variable)
Declared within the class and Represent Object State
Shared between different object of the same class.
Gets default value and cannot be reinitialized within the class
Local variables:
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block
is entered, and the variable will be destroyed once it exits the
method, constructor or block.
Access modifiers cannot be used for local variables.
test.pupAge();
}
}
Instance variables:
Instance variables are declared in a class, but outside a method,
constructor or any block.
When a space is allocated for an object in the heap, a slot for each
instance variable value is created.
Instance variables are created when an object is created with the use
of the keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than
one method, constructor or block, or essential parts of an object's
state that must be present throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and
block in the class. Normally, it is recommended to make these
variables private (access level). However visibility for subclasses
can be given for these variables with the use of access modifiers.
Instance variables have default values. For numbers the default
value is 0, for Booleans it is false and for object references it is null.
Values can be assigned during the declaration or within the
constructor.
Instance variables can be accessed directly by calling the variable
name inside the class. However within static methods and different
class ( when instance variables are given accessibility) should be
called using the fully qualified name .
ObjectReference.VariableName.
Example:
import java.io.*; public
class Employee{
// salary variable is visible in Employee class only. private
double salary;
// The name variable is assigned in the constructor. public
Employee (String empName){
name = empName;
}
// The salary variable is assigned a value. public
void setSalary(double empSal){ salary = empSal;
}
// This method prints the employee details. public void
printEmp(){ System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){ Employee
empOne = new Employee("Ransika");
empOne.setSalary(1000); empOne.printEmp();
}
}
Class/static variables:
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final and static.
Constant variables never change from their initial value.
Static variables are stored in static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is like instance variables. However, most static variables are
declared public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value
is 0; for Booleans, it is false; and for object references, it is null. Values can
be assigned during the declaration or within the constructor. Additionally
values can be assigned in special static initializer blocks.
Static variables can be accessed by calling with the class name .
ClassName.VariableName.
When declaring class variables as public static final, then variables names
(constants) are all in upper case. If the static variables are not public and
final the naming syntax is the same as instance and local variables.
Example:
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development "; public
static void main(String args[]){
salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}
This would produce the following result:
Development average salary:1000
Note: If the variables are access from an outside class the constant should be accessed as
Employee.DEPARTMENT
21
Variable Declaration
<Data type> [variable name][=Row data or expression]
The type of information is listed first, followed by the name of the variable.
The following are all examples of variable declarations:
int loanLength; boolean gameOver;
If you are creating several variables of the same type, you can declare
all of them in the same statement by separating the variable names
with commas.
String street, city, state;
Naming Variables
Variable names in Java must start with a letter, an underscore
character (“_”), or a dollar sign (“$”).
They cannot start with a number.
After the first character, variable names can include any combination
of letters or numbers.
it’s important to remember that Java is case sensitive
Rule of thumb
o The first letter of the variable name is lowercase.
o Each successive word in the variable name begins with a capital
letter.
o All other letters are lowercase.
Assigning Values to Variables
After a variable has been declared, a value can be assigned to it with
the assignment operator, which is an equal sign (“=”).
The following are examples of assignment statements:
o idCode = 8675309;
o accountOverdrawn = false;
Methods
Methods define an object’s behavior—that is, anything that happens when
the object is created as well as the various tasks the object can perform
during its lifetime.
Defining Methods
In Java, a method definition has four basic parts:
The name of the method
A list of parameters
The type of object or primitive type returned by the
method
22
The body of the method
The returnType is the primitive type or class of the value returned by the
method.
It can be one of the primitive types, a class name, or void if the
method does not return a value at all.
The method’s parameter list is a set of variable declarations separated by
commas and set inside parentheses.
These parameters become local variables in the body of the method,
receiving their values when the method is called.
Constructor
A class contains constructors that are invoked to create objects from
the class blueprint.
Constructor declarations look like method declarations—except that
they use the name of the class and have no return type. For example,
Student class may have one or more constructor(s):
The this keyword
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being called.
You can refer to any member of the current object from within an instance
method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field is
shadowed by a method or constructor parameter.
Java Operator
An operator is a symbol that operates on one or more arguments to
produce a result.
Java provides a rich set of operators to manipulate variables.
23
TYPES OF OPERATORS
Assignment Operators
Increment Decrement Operators
Arithmetic Operators
Bitwise Operators
Relational Operators
Logical Operators
Ternary Operators
Comma Operators
Instance of Operators
1. ASSIGNMENT OPERATORS
o The assignment statements has the following syntax:
<variable> = <expression>
24
a=a+ 1; a++; or ++a;
3. ARITHMETIC OPERATORS
The arithmetic operators are used to construct mathematical
expressions as in algebra.
Their operands are of numeric type.
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
4. BITWISE OPERATORS
Java's bitwise operators operate on individual bits of integer (int and
long) values.
25
If an operand is shorter than an int, it is promoted to int before doing
the operations.
5. RELATIONAL OPERATORS
A relational operator compares two values and determines the
relationship between them.
For example, != returns true if its two operands are unequal.
Relational operators are used to test whether two values are equal,
whether one value is greater than another, and so forth.
class Vehicle {}
public class Car extends Vehicle
{
public static void main(String args[])
{
Vehicle a = new Car();
boolean result =
a instanceof Car; System.out.println( result);
}
}
Chapter – 3
Conditional Statement, Repetition Statement and Array
2.1 Decision and Repetition Statements
The Java keywords for controlling program flow are nearly identical to C++. This is
one of the most obvious ways in which Java shows its legacy as a derivative of this
language. In this section, you will see how to use Java's control flow statements.
2.1.1. Decision / Conditional Statements / Selection Statment
The Java language provides two alternative statements -if statements and switch
statements - for selecting among the given alternatives.
The if Statement
The Java if statement is a test of any Boolean expression. If the Boolean expression
evaluates to true, the statement following the if statement is executed. On the other
hand, if the Boolean expression evaluates to false, the statement following the if is not
executed. For example, consider the following code fragment:
30
import java.util.Date;
if (today.getDay == 0) then
System.out.println("It is Sunday.");
This code uses the java.util.Date package and creates a variable named today that will
hold the current date. The getDay member method is then applied to today and the
result compared to 0. A return value of 0 for getDay indicates that the day is Sunday,
so if the Boolean expression today.getDay = = 0 is true, a message is displayed. If today
isn't Sunday, no action occurs. In Java, the expression used within an if statement
must evaluate to a Boolean.
The Java developers included an else statement that can be executed whenever an if
statement evaluates to false. This can be seen in the following sample code:
import java.util.Date;
if (today.getDay == 0) then
System.out.println("It is Sunday.");
else
In this case, the same message will be displayed whenever it is Sunday, but a different
message will be displayed whenever it is not Sunday. Both examples so far have only
shown the execution of a single statement within the if or the else cases. By enclosing
the statements within curly braces, you can execute as many lines of code as you'd
like. This can be seen in the following example that makes some suggestions about
how to spend each day of the week:
31
import java.util.Date;
if (today.getDay == 0) then {
System.out.println("It is Sunday.");
else {
Because it's possible to execute whatever code you desire in the else portion of an
if…else block, you may have already reasoned that it is possible to execute another if
statement inside the else statement of the first if statement. This is commonly known
as an if…else if…else block, an example of which follows:
import java.util.Date;
if (today.getDay == 0) then
System.out.println("It is Sunday.");
System.out.println("It is Monday.");
System.out.println("It is Tuesday.");
System.out.println("It is Wednesday.");
32
else if (today.getDay == 4) then
System.out.println("It is Thursday.");
System.out.println("It is Friday.");
else
switch (today.getDay) {
case 0: // Sunday
System.out.println("It is Sunday.");
break;
case 1: // Monday
System.out.println("It is Monday.");
break;
case 2: // Tuesday
System.out.println("It is Tuesday.");
break;
33
case 3: // Wednesday
System.out.println("It is Wednesday.");
break;
case 4: // Thursday
System.out.println("It is Thursday.");
break;
case 5: // Friday
System.out.println("It is Friday.");
break;
default: // Saturday
System.out.println("All done!");
You should have noticed that each day has its own case within the switch. The
Saturday case (where today.getDay = 6) is not explicitly given but is instead handled by
the default case. Any switch block may include an optional default case that will
handle any values not caught by an explicit case.
Within each case, there can be multiple lines of code. The block of code that will
execute for the Friday case, for example, contains three lines. The first two lines will
simply display informational messages, but the third is a break statement. The
keyword break is used within a case statement to indicate that the flow of the program
should move to the first line following the switch block. In this example, break appears
as the last statement in each case except the default and will cause program execution
34
to move to the line that prints "All done!" The break statement was left out of the
default block because by that point in the code, the switch block was ending, and there
was no point in using an explicit command to exit the switch.
If, as the previous example seems to imply, you always need to include a break
statement at the end of each block, why not just leave break out and have Java assume
that after a block executes, control should move outside the switch block? The answer
is that there are times when you do not want to break out of the switch statement after
executing the code for a specific case value. For example, consider the following code
that could be used as a scheduling system for physicians:
import java.util.Date;
switch (today.getDay) {
case 0: // Sunday
case 3: // Wednesday
case 6: // Saturday
break;
case 2: // Tuesday
case 1: // Monday
case 4: // Thursday
case 5: // Friday
break;
35
}
System.out.println("All done!");
This example illustrates a couple of key concepts about switch statements. First, you'll
notice that it is possible to have multiple cases execute the same block of code, as
follows:
case 0: // Sunday
case 3: // Wednesday
case 6: // Saturday
break;
This code will result in the message "It's Golf Day" being displayed if the current day
is Wednesday, Saturday, or Sunday. If you collect the three cases together without
any intervening break statements, each will execute the same code. But consider what
happens on Tuesday when the following code executes:
case 2: // Tuesday
Certainly a reminder about the message match will be displayed, but this case doesn't
end with a break statement. Because Tuesday's code doesn't end with a break statement,
the program will continue executing the code in the following cases until a break is
encountered. This means that Tuesday's code flows into the code used for Monday,
Thursday, and Friday as shown in the following:
case 2: // Tuesday
case 1: // Monday
case 4: // Thursday
36
case 5: // Friday
break;
This will result in the following messages being displayed every Tuesday:
Tennis at 8:00 am
On Monday, Thursday, and Friday, only the latter message will display.
In addition to writing switch statements that use integer cases, you can use character
values as shown in the following example:
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch and it must be a
constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case
Iteration
37
Iteration is an important concept in any computer language. Without the ability to
loop or iterate through a set of values, our ability to solve real-world problems would
be severely limited. Java's iteration statements are nearly identical to those found in C
and C++ and include for loops, while loops, and do…while loop
38
The for Statement
The first line of a for loop enables you to specify a starting value for a loop counter,
specify the test condition that will exit the loop, and indicate how the loop counter
should be incremented (decremented) after each pass through the loop. The syntax of
a Java for statement is as follows:
for (initialization; testExpression; incremement)
statement
In this example, the initialization statement of the for loop sets count to 0. The test
expression, count < 100, indicates that the loop should continue as long as count is less
than 100. Finally, the increment statement increases the value of count by one. As long
as the test expression is true, the statement following the for loop setup will be
executed, as follows:
System.out.println("count = " + count);
Of course, you probably need to do more than one thing inside the loop. This is as
easy to do as using curly braces to indicate the scope of the for loop, as shown in the
following:
int count;
YourMethod(count);
39
System.out.println("Count = " + count);
One nice shortcut that can be taken with a Java for loop is to declare and initialize the
variable used in the loop. For example, in the following code, the variable count is
declared directly within the for loop:
for (int count=0; count<100; count++)
It may look like an unimportant difference whether you declare a variable before a for
loop or within the loop. However, there are advantages to declaring the variable
within the loop. First, it makes your intention to use the variable within the loop clear.
If the variable is declared above the for loop, how will you remember (and how will
future programmers know) that the variable was intended to be used only within the
loop? Second, a variable declared within the for loop will go out of scope at the end of
the loop. This means you could not write the following code:
for (int count=0; count<100; count++)
The last line cannot find a variable named count because count goes out of scope when
the for loop terminates. This means that, in addition to making the intended purpose of
the variable clearer, it is also impossible to accidentally bypass that intent and use the
variable outside the loop.
You can also leave out portions of the first line of a for loop. In the following example,
the increment statement has been left out:
40
for (int count=0; count<100; ) {
count += 2;
Of course, leaving the increment statement out of the for loop declaration in this
example doesn't achieve any useful purpose since count is incremented inside the loop.
It is possible to get even fancier with a Java for loop by including multiple statements
or conditions. For example, consider the following code:
for (int up=0, down = 20; up < down; up++, down -= 2 ) {
This loop starts the variable up at 0 and increments it by 1. It also starts the variable
down at 20 and decrements it by 2 for each pass through the loop. The loop continues
until up has been incremented enough that it is equal to or greater than the variable
down.
The test expression portion of a Java for loop can be any Boolean expression. Because
of this, it does not need to be a simple test (x < 10), as shown in the preceding
examples. The test expression can be a method call, a method call combined with a
value test, or anything that can be phrased as a Boolean expression. For example,
suppose you want to write a method that will display a message indicating the first
year since World War II that the Chicago Cubs appeared in the World Series. You
could do this as follows:
The method DidCubsPlayInWorldSeries is passed an integer value indicating the year
and returns a Boolean value that indicates whether or not the Cubs made it to the
41
World Series in that year. This method is an example of the switch statement shown
earlier in this chapter.
The while Statement
Related to the for loop is the while loop. The syntax for a while loop is as follows:
while(booleanExpression){
Body statement
As you can tell from the simplicity of this, the Java while loop does not have the built-
in support for initializing and incrementing variables that its for loop does. Because of
this, you need to be careful to initialize loop counters prior to the loop and increment
them within the body of the while loop. For example, the following code fragment will
display a message five times:
int count = 0;
count++;
loop is as follows:
do {
statement
} while (booleanExpression);
42
This is similar to a while loop except that a do…while loop is guaranteed to execute at
least once. It is possible that a while loop may not execute at all depending on the test
expression used in the loop. For example, consider the following method:
public void ShowYears(int year) {
year++;
This method is passed a year value, then loops over the year displaying a message as
long as the year is less than 2000. If year starts at 1996, then messages will be
displayed for the years 1996, 1997, 1998, and 1999. However, what happens if year
starts at 2010? Because the initial test, year < 2000, will be false, the while loop will
never be entered. Fortunately, a do…while loop can solve this problem. Because a
do…while loop performs its expression testing after the body of the loop has executed
for each pass, it will always be executed at least once. This is a very valid distinction
between the two types of loop, but it can also be a source of potential errors.
Whenever you use a do…while loop, you should be careful to consider the first pass
through the body of the loop.
Jumping
Of course, it is not always easy to write all of your for, while and do…while loops so
that they are easy to read and yet the loops terminate on exactly the right pass through
the loop. Java makes it easier to jump out of loops and to control other areas of
program flow with its break and continue statements.
43
The break Statement
Earlier in this chapter, you saw how the break statement is used to exit a switch
statement. In a similar manner, break can be used to exit a loop. As an example of this,
consider the following code:
int year = 1909;
break;
This example shows a while loop that will continue to execute until it finds a year that
the Chicago Cubs won the World Series. Because they haven't won since 1908 and
the loop counter year starts with 1909, it has a lot of looping to do. For each year they
didn't win, a message is displayed. However, even die-hard Cubs fans will eventually
give up and change allegiances to the Chicago White Sox. In this example, if the year
is 3000 or later, a message is displayed and then a break is encountered. The break
statement will cause program control to move to the first statement after the end of
the while loop. In this case, that will be the following line:
System.out.println("Loop exited on year " + year);
int timesWon = 0;
if (DidCubsPlayInWorldSeries(year) = false)
continue;
if (DidCubsWinWorldSeries(year)) {
timesWon++;
In this case, a for loop is used to iterate through the years from 1900 to 2000. The first
line within the loop tests to see if the Cubs played in the World Series. If they didn't,
the continue statement is executed. This moves program control back to the for loop.
At that point, year is incremented and the expression year <= 2000 is retested. If year is
less than or equal to 2000, the loop continues. If, however, DidCubsPlayInWorldSeries
equals true, then the continue statement is skipped, and the next test is performed to
see if the Cubs won that year.
Infinite Loops
int count = 1;
System.out.println(count);
count = count - 1;
This loop will continue executing until the user externally interrupts the
program.
2.2.1. Advanced Arrays
Introduction
46
• Arrays are fixed-length entities—they remain the same length once
they are created, although an array variable may be reassigned such
that it refers to a new array of a different length.
Treated as objects
Cause:
Cause :
Declaring arrays
47
Declaring arrays…Syntax
ArrayType[ ] arrayVariable;
E.g. 1
Int[] count
String[] names;
Double[] marks;
Creating arrays…Syntax
E.g.
count = new int[3]; Creating Array with size 3
names = new String [12];
Initializing arrays…Syntax
ArrayType arrayVariable[ ]={val1,val2, …, valn};
a comma-separated list of expressions
48
Or, You can use loops to initialized arrays.
Declaring
arrayType arrayVariable[][];
arrayVariable=new arrayType[rowSize][columnSize];
E.g.
int calander[][];
calander=new int[13][30];
49
Size
E.g.
int count=x.length;
int n=x[2].length;
java.util.Arrays
51
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can
find many objects around us, Cars, Dogs, Humans, etc. All these objects have a
state and behavior. If we consider a dog, then its state is - name, breed, color, and
the behavior is - barking, wagging, running If you compare the software object
with a real world object, they have very similar characteristics. Software objects
also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods. So in software development, methods operate on
the internal state of an object and the object- to-object communication is done via
methods.
Classes in Java:
A class is a blue print from which individual objects are created. A sample of a class
is given below:
public class
Dog{ String breed;
}
void hungry(){
}
void sleeping(){
}
}
A class can contain any of the following variable types.
Local variables: Variables defined inside methods, constructors or blocks
52
are called local variables. The variable will be declared and
53
initialized within the method and the variable will be destroyed when the
method has completed.
Instance variables: Instance variables are variables within a class but
outside any method. These variables are instantiated when the class is loaded.
Instance variables can be accessed from inside any method, constructor or
blocks of that particular class.
Class variables: Class variables are variables declared within a class,
outside any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Below mentioned are some of the important topics that need to be discussed when
looking into classes of the Java Language.
Constructors:
When discussing about classes, one of the most important subtopic would be
constructors. Every class has a constructor. If we do not explicitly write a
constructor for a class the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor.
Example of a constructor is given below:
public class
Puppy{ public
Puppy(){
}
public Puppy(String name){
// This constructor has one parameter, name.
54
}
55
Creating an Object:
}
public static void main(String[]args){
// Following statement would create an object myPuppy
Puppy myPuppy =new Puppy("tommy");
}
}
If we compile and run the above program, then it would produce the following result:
56
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an
instance variable the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
Example:
This example explains how to access instance variables and methods of a class:
public class
Puppy{ int puppyAge;
}
public void setAge(int
age ){ puppyAge = age;
}
public int getAge(){
System.out.println("Puppy's age is :"+ puppyAge );
return puppyAge;
71
}
public static void main(String[]args){
/* Object creation *
Puppy myPuppy =newPuppy("tommy");
/* Call class method to set puppy's age */
myPuppy.setAge(2);
}
}
If we compile and run the above program, then it would produce the following result:
PassedName is:tommy
Puppy's age is :2
Variable Value :2
72
Source file declaration rules:
As the last part of this section, let‘s now look into the source file declaration rules.
These rules are essential when declaring classes, import statements and package
statements in a source file.
There can be only one public class per source file.
A source file can have multiple nonpublic classes.
The public class name should be the name of the source file as well which
should be appended by .java at the end. For example: The class name is.
public class Employee{} Then the source file should be as Employee.java.
If the class is defined inside a package, then the package statement should be
the first statement in the source file.
If import statements are present then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the source
file.
Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.
Classes have several access levels and there are different types of classes;
abstract classes, final classes, etc. I will be explaining about all these in the
access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special
classes called Inner classes and Anonymous class
73
1. INHERITANCE
Inheritance can be defined as the process where one object acquires the
These words would determine whether one object IS-A type of another.
By using these keywords, we can make one object acquire the properties
of another
The idea behind inheritance in java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class,
you can reuse methods and fields of parent class, and you can add new
74
Syntax of Java Inheritance
The extends keyword indicates that you are making a new class that derives
In the terminology of Java, a class that is inherited is called a super class. The
class Employee{
float salary=40000;
int bonus=10000;
Programmer();
System.out.println("Bonus of Programmer
is:"+p.bonus);
75
}
Output:
In the above example, Programmer object can access the field of own class
76
Chapter 5
Category of Classes on the Basis of Inheritance
1. Super class
(base/parent/driver/inheritance/ ancestor class).
Top located class
Service provider (its properties accessed by all its lower level class).
2. Intermediate class
(mediating/dual class).
Middle located class
Having Dual policy (obtain properties of upper level class and transmit properties
to lower level class).
3. Child class
(sub/associate/derived/inherited class).
Bottom located class much benefitted class much loaded class
properties of child class as well as
class and parent class can beaccessed by
only the object of child class.
Relation between classes
TYPES of INHERITANCE
1. Single Inheritance
A structure having one and only one parent as well
as child class.
Child class is authorized to access the property of parent class
77
Chapter 5
2. Multilevel Inheritance
Standard structure of Single Inheritance having one Parent, one or more
intermediate and one child classes.
Child class as well as intermediate class may access the properties of upper level
classes.
3. Hierarchical Inheritance
A structure having one parent and more child class.
Child classes must be connected with only Parent class.
78
Chapter 5
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by using the
extends keyword. To see how, let’s begin with a short example. The following program
creates a superclass called A and a subclass called B. Notice how the keyword extends is
used to create a subclass of A.
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
79
Chapter 5
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
80
Chapter 5
}
Overridden methods are methods that are redefined within an inherited or subclass. They
have the same signature and the subclass definition is used.
Casting Objects
One of the difficulties of using a superclass array to hold many instances of subclass objects
is that one can only access properties and methods that are in the superclass (ie. common to
all). By casting an individual instance to its subclass form, one can refer to any property or
method. But first take care to make sure the cast is valid by using the instanceof operator.
Then perform the cast. As an example using the above Animal class:
Casts to subclass can be done implicitely but explicit casts are recommended. Casts to
superclass must be done explicitly. Casts cannot be made between sibling classes.
Method overloading and method overriding in Java
Method overloading and method overriding uses concept of Polymorphism in Java where
method name remains same in two classes but actual method called by JVM depends upon
object at run time and done by dynamic binding in Java. Java supports both overloading and
overriding of methods. In case of overloading method signature changes while in case of
overriding method signature remains same and binding and invocation of method is decided
on runtime based on actual object. This facility allows Java programmer to write very
flexibly and maintainable code using interfaces without worrying about concrete
implementation. One disadvantage of using Polymorphism in code is that while reading code
you don't know the actual type which annoys while you are looking to find bugs or trying to
debug program. But if you do Java debugging in IDE you will definitely be able to see the
actual object and the method call and variable associated with it.
Method Overriding
82
Chapter 5
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a subclass, it will always refer
to the version of that method defined by the subclass. The version of the method defined by
the superclass will be hidden. Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
83
Chapter 5
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you wish
to access the superclass version of an overridden method, you can do so by using super. For
example, in this version of B, the superclass version of show( ) is invoked within the
subclass’ version. This allows all instance variables to be displayed.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
output:
i and j: 1 2
k: 3
84
Chapter 5
Here, super.show( ) calls the superclass version of show( ).
Method overriding occurs only when the names and the type signatures of the two methods
are identical. If they are not, then the two methods are simply overloaded. For example,
consider this modified version of the preceding example:
// Methods with differing type signatures are overloaded – not
// overridden.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
System.out.println(msg + k);
}
85
Chapter 5
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
88
Chapter 5
89
90
91
92
93
94
95
96
97
98
99
1