Java 2
Java 2
int y = '\n';
System.out.println(y); // prints 10
}
}
You can try for other escape characters also what their ASCII codes.
Java also comes escape sequences and the list if given here under.
In the following program, the instance variables are static. As they are
static, they called from main() without the help of an object.
The previous program can be modified where instance variables are not
static. Then you require an object to call them from static main()
method.
From JDK 1.7, main() method is required to execute static block. Anyhow,
static block is called before main() is executed.
Abstraction
Encapsulation
Polymorphism
1. Abstraction
Abstraction means using the equipment (or code) without knowing the
details of working. For example, you are using your mobile phone without
knowing how a mobile operates internally. Just a click on a button
connects to your friend. This is abstraction. That is, the details of
mobile mechanism are abstracted. Similarly we use the code of somebody to
get the functionality without knowing how the code is written or working.
For example, you are using printf() function to write to the DOS prompt
without the awareness of what the code of printf(). One of the ways of
achieving abstraction is inheritance. Through inheritance a subclass can
use the super class methods as if they belong to it without caring their
implementation details.
2. Encapsulation
Object-oriented concepts borrowed many terms from other technologies like
encapsulation (from pharmaceuticals), inheritance (from biology), cloning
(from genetics) and polymorphism (from biology) etc. Placing a powdered
drug in a gelatin capsule and sealing it is known as encapsulation. With
encapsulation, a Pharmacist hides the properties of a drug like its taste
and color from the patient. Similar meaning is in OOPs also.
Encapsulation hides the implementation details of coding; other way it is
abstraction. With abstraction, implementation of information is hidden.
3. Polymorphism
Polymorphism is a Greek term and means many forms of the same ("poly"
means many and "morphism" means forms). It is an OOP paradigm where one
method can be made to give different outputs (functionalities) when
called at different times. Polymorphism is two ways – static polymorphism
where methods are binded at compile time and dynamic polymorphism where
methods are binded dynamically at runtime. The same person is called as
an officer (in office), husband (in house) and player (in cricket team).
The person can be treated as base class. Extra subclasses can be added by
hierarchical inheritance like son etc.
Two concepts existed in the minds of Java designers from the day one of
development – to make the language simple and easy to practice and
platform-independent. The basic entity of Java coding is a "class". A
class is delimited by a pair of braces, { and }. All the code resides
within a class. The name of the class is the name with which the whole
code is known. An object is a handle to manipulate the whole code of the
class. A class can comprise of constructors, variables, methods and some
blocks of code (like static blocks) etc.
Open a file with the same name of that of the class. Say, the name of the
class, you would like to write is "Wihses", then open the file as
"Wishes.java" as follows.
import java.lang.*;
public class Wishes
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Best wishes");
}
}
Just save the file after typing the code.
Compilation
Execution
Type the following command at the DOS prompt to execute the code.
java" is a Java command of execution. That is, you are invoking the Java
interpreter to execute the bytecode. You get the output at the DOS
prompt.
import java.lang.*;
The main() method comes with many decorative paraphernalia and each one
conveys some meaning to the compiler. The "static" means the main()
method can be called without the help of an object. "void" keyword means
the main() method does not return a value. The main() takes a String
array as parameter and is used later to access command-line arguments.
System.out.println(mangoes);
Java does not support operator overloading but designers overloaded the +
operator. In Java coding, + operator can be used both for addition and
concatenation. In the above statement, + is used for the concatenation of
" and " and also used for addition as in "mangoes+bananas". To get the
correct values, if there exists a string in println statement, the
variables that are to be added are to be placed in parenthesis. Observe,
mangoes+bananas are placed within parenthesis.
A number of objects can be created for a single class. Each object can be
given properties through variables. OOP permits to have a separate set of
values for each object. Methods increase the reusability of code. Methods
of Java are called as procedures or functions in other languages.
In the above Employee class, one local variable "company" and two
instance variables "salary" and "department" are declared. They are used
from the static main() method. As you can observe from the above program,
to call the local variable "company", object "emp1" is not used; but to
call the instance variables emp1 is used. If not, the compiler raises
errors (as in the last statement).
Employee emp1 = new Employee();
First time we are creating an object of a class. Note the syntax. The
class name comes two times. Employee is the class and Employee() is known
as a constructor. “new” keyword is used to create an object.
emp1.salary = 8000;
emp1.department = “Finance”;
In the above two statements, to give values for the instance variables
salary and department, object emp1 is used.
System.out.println(company);
System.out.println(emp1.salary);
System.out.println(emp1.department);
To print the local variable company, object is not used. To print the
instance variables, object emp1 is used.
Using Methods
The procedures and functions are known as methods in Java. The methods
scope is for the whole class. Now here, you can make a small difference.
A function in C-lang can be called without object but a method is to be
called with an object. The first line of a method declaration is known as
"method signature". A Java method signature may comprises of an access
specifier, one or two optional access modifiers, return type, name,
optional parameter list and also optional exceptions the method can
throw. The parameter or a return type can be a variable, an object or an
array. Following program illustrates.
The above code involves two methods – nature() and total(). The nature()
method just prints a message and does not have parameters and return
type. But total() method takes three parameters and a return type. The
return type must be only one value for a method. You will not see any new
information here, it is same as C/C++. Observe, the methods are called
with object emp1 (like instance variables). To make the program simple,
instance variables are not used. We will write another program later with
instance variables and methods. The global variables in Java are known as
"instance variables".
void display() { }
void display(int x) { }
The above two functions of the same name display() raises compilation
error in C-lang as C cannot differentiate the same functions depending on
their parameters. But C++ and Java can differentiate the same named
functions depending on their parameters. The same method declared, in the
same class, a number of times, but with different parameters is known as
"method overloading". With method overloading, the same method called at
different times gives different outputs (functionalities).
The above two eat() methods differ in their return type but not in
parameters. Compiler cannot judge which is to be called depending on the
return types; judges only on the parameter list. The above statements
raise a compilation error. The return type may or may not be the same in
method overloading.
Static Binding
Static Polymorphism
To go before into the subject, just read the program twice. You may guess
some values how they are printed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Officer
{
int salary;
public static void main(String args[])
{
Officer o1 = new Officer();
Officer o2 = new Officer();
o1.salary = 5000;
o2.salary = 6000;
System.out.println("Salary of o1 before initially Rs." +
o1.salary);// 5000
System.out.println("Salary of o2 before initially Rs." +
o2.salary);// 6000
o1.salary = 7000;
System.out.println("Salary of o1 after changing o1 Rs.:" +
o1.salary);// 7000
System.out.println("Salary of o2 after changing o1 Rs." +
o2.salary);// 6000
o2.salary = 8000;
System.out.println("Salary of o1 after changing o2 Rs.:" +
o1.salary);// 7000
System.out.println("Salary of o2 after changing o2 Rs." +
o2.salary);// 8000
}
}
Now let us see how to assign the properties of one object to another by
modifying the previous Officer program.
o1.salary = 6000;
System.out.println("o1 salary after changing o1 Rs." + o1.salary); //
6000
System.out.println("o2 salary after changing o1 Rs." + o2.salary); //
5000
o3.salary = 7000;
o4 = o3; // assigning object to
object
System.out.println("o3 initial salary Rs." + o3.salary); // 7000
System.out.println("o4 inital salary Rs." + o4.salary); // 7000
o3.salary = 8000;
System.out.println("o3 salary after changing o3 Rs." + o3.salary);
// 8000
System.out.println("o4 salary after changing o3 Rs." + o4.salary);
// 8000
}
}
In the previous, Officer1 program, all the code is written in the main()
method only. You may get output but it is against coding principles.
Coding principles say, keep the main() method as thin as possible by
placing less code. Limit the main() method just to create objects and
calling the methods. Write any code in a method and call the method from
the main(). This increases the reusability, readability and debugging
becomes easier. Let us modify the previous program.
o1.display(5000);
o2.display(6000);
System.out.println(o1.salary); // 5000
System.out.println(o2.salary); // 6000
}
}
We have seen earlier with, Using Methods program, how to use methods in
Java, but it was without using instance variables. Now let us use
instance variables through methods.
Even though the code looks simple, there is a necessity to explain how
vwm.a called from main() method printed 300 and not 100. What are the
principles involved and what is going actually inside?
To make coding simple, designers share a lot of work which we are
supposed to do ourselves. Whenever a method is called with an object,
like vwm.show(), the instance variables inside the method are linked with
the object implicitly. For this reason, the a called from show() becomes
vwm.a. One more principle is, whenever an instance variable is called
with an object, a global location is created for vwm.a. This location
even though created through show() method, the location can be accessed
by any other method, but with vwm object only. The location a is private
to object vwm only. This is how encapsulation is maintained. If another
object is there like vwm1 and called the show() as vwm1.show(), then
there creates a location on the name of vwm1.a and this location is
private to vwm1.
Now a value in show() method is changed from 100 to 300. But a is nothing
but vwm.a. Earlier value in the location is 100 and now changed to 300.
By the time control comes to vwm.a in main() method, the value of vwm.a
is already changed. For this reason, vwm.a from main() method prints 300.
To get the concept more clearer, let us write one more program with an
additional explanation of data binding, data hiding and encapsulation.
"this" keyword refers an object, to say, the current object. Observe the
following program and pay attention to this.salary.
One of the features of Java is "Java does not support garbage values". If
a variable is used without a value assigned, it is either compilation
error or takes a default value. If a local variable is not given a value
and still used in the program it is a compilation error. But in case of
an instance variable, it takes a default value. For example, an integer
variable takes 0 by default. Following program illustrates.
In the above code, price, rate and raining are instance variables and
printed default values. But local variable marks is placed in comments.
If comments are removed and compiled the program, it raises compilation
error. The following list gives the default values for instance
variables.
Generally, you know earlier, to call a method and also a variable from
the static main(), you require an object. Of course it is right but not
with static methods and static variables. static modifier modifies the
access and allows to call without the help of an object. "static" keyword
can be applied to instance variables and methods and not with classes and
also not with local variables..
The same style of static variables is followed with static methods also
and can be called in three ways. Following program explains.
Class Variable
main() method is declared as static to allow the JVM to call the main()
without the help of an object. JVM is a separate process and to call the
method of another process (your program), it requires an object. As the
execution starts from the main(), the JVM cannot create an object without
entering the main() method. If the main() method is allowed to call
without the need of an object, the JVM can create hundreds of objects
once enters the main(). For this reason, main() is declared as static.
We know earlier every object will have its own copy of variables. But
with static variables, it is very different. A static variable location
is shared (or accessed or pointed) by all the objects of the class. The
result is, if one object changes the value, all the other objects also
get affected. With static variables, no encapsulation exists. Observe the
following program.
System.out.println(d1.x); // 10
System.out.println(d2.x); // 10
d1.x = 20;
System.out.println(d2.x); // 20
d2.x = 30;
System.out.println(d1.x); // 30
System.out.println(x); // 30
}
}
Observe, average and show() are static members of the class Demo and are
called without the need of an object. marks and display() are non-static
members and are called with object d1.
class Bird
{
public void eat()
{
System.out.println("All birds eat for their metabolic
activities");
}
}
public class Parrot
{
public static void main(String args[])
{
Bird b1 = new Bird();
b1.eat();
}
}
Before going to composition, let us know how to write the above code and
on which name the Java file should be opened. The rule says, in a single
source code, if a number of classes exist, only one class can be public.
The file name must be of that class which is public. In the code, two
classes exist – Bird and Parrot. As Parrot is public, the file opened
must be on the name of "Parrot.java". So, open "Parrot.java" file and
write the source code and compile as usual as "javac Parrot.java" and
execute as "java Parrot".
The Parrot class, in its main() method, created an object of Bird and
called Bird's method eat(). Here, Bird and Parrot are no way connected or
related (I mean, no inheritance). Just they happened to be in the same
folder. This feature we call as "composition". Creating another class
object in our class and calling other class methods is known as
composition.
There is one more concept called aggregation which differs slightly from
composition. To know their narrow difference see Aggregation and
Composition.