2. Classes and Objects are basic concepts of Object Oriented Programming
which revolve around the real life entities.
A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to
all objects of one type. In general, class declarations can include these
components.
Modifiers : A class can be public or has default access.
Class name: The name should capitalized by convention.
Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
Interfaces(if any): A comma-separated list of interfaces implemented by
the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects.
Fields are variables that provides the state of the class and its objects
methods are used to implement the behavior of the class and its objects.
CLASS
3. It is a basic unit of Object Oriented Programming and represents the
real life entities. A typical Java program creates many objects, which
as you know, interact by invoking methods. An object consists of :
State : It is represented by attributes of an object. It also reflects the
properties of an object.
Behavior : It is represented by methods of an object. It also reflects the
response of an object with other objects.
Identity : It gives a unique name to an object and enables one object to
interact with other objects.
Ex: car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
When an object of a class is created, the class is said to
be instantiated.
All the instances share the attributes and the behavior of the class. But
the values of those attributes, i.e. the state are unique for each object.
A single class may have any number of instances.
OBJECT
4. public class MyClass
{
int x = 5;
public static void main(String[] args)
{
MyClass myObj = new MyClass();//creating object
System.out.println(myObj.x);
}
}
The objects that are not referenced anymore will be destroyed
by Garbage Collector of java.
CREATING THE CLASS AND OBJECT
5. public class MyClass
{
int x = 5;
}
Member variables in a
class—these are
called fields/attribute
.
Variables in a method
or block of code—
these are called local
variables.
class OtherClass
{
public static void main(String[] args)
{
MyClass myObj = new MyClass();
System.out.println(myObj.x);
myObj.x=25;
System.out.println(myObj.x);
}
}
6. By Reference
public class MyClass
{
int x = 5;
public static void main(String[] args)
{
MyClass myObj = new MyClass();//creating object
System.out.println(myObj.x);
myObj.x=25;
System.out.println(myObj.x);
}
}
3 WAYS TO INITIALIZE OBJECT
7. Initialize through methods
Class MyClass{
int i;
void setValue(int x){
i=x;
}
void getValue()
{
System.out.println(i);
}
Public static void main(String[] arg)
{
MyClass myobj1=new MyClass();
myobj1.setValue(10);
myobj1.getValue();
}
}
8. Using Constructors:
Class MyClass{
int i;
MyClass()
{
i=10;
}
Public static void main(String[] arg)
{
MyClass myobj1=new MyClass();
System.out.println(myobj1.i);
}
}
9. The name must not contain any white spaces.
The name should not start with special characters like & (ampersand), $ (dollar), _
(underscore).
Class
• It should start with the uppercase letter.
• It should be a noun such as Color, Button, System, Thread, etc.
• Use appropriate words, instead of acronyms.
Example: - public class Employee { //code snippet }
Interface
• It should start with the uppercase letter.
• It should be an adjective such as Runnable, Remote, ActionListener.
• Use appropriate words, instead of acronyms.
Example: - interface Printable { //code snippet }
Method
• It should start with lowercase letter.
• It should be a verb such as main(), print(), println().
• If the name contains multiple words, start it with a lowercase letter followed by
an uppercase letter such as actionPerformed().
JAVA NAMING CONVENTIONS
10. Variable
• It should start with a lowercase letter such as id, name.
• It should not start with the special characters like & (ampersand), $
(dollar), _ (underscore).
• If the name contains multiple words, start it with the lowercase letter
followed by an uppercase letter such as firstName, lastName.
• Avoid using one-character variables such as x, y, z.
Package
• It should be a lowercase letter such as java, lang.
• If the name contains multiple words, it should be separated by dots (.)
such as java.util, java.lang.
Constant
• It should be in uppercase letters such as RED, YELLOW.
• If the name contains multiple words, it should be separated by an
underscore(_) such as MAX_PRIORITY.
• It may contain digits but not as the first letter.
CONTD…
11. Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within
the package. It cannot be accessed from outside the package.
If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within
the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from
outside the package.
Public: The access level of a public modifier is everywhere. It
can be accessed from within the class, outside the class,
within the package and outside the package.
ACCESS SPECIFIERS
12.
13. A constructor in Java is a special method that is used to initialize
objects.
The constructor is called when an object(instance) of a class is
created. It can be used to set initial values for object attributes
At the time of calling constructor, memory for the object is
allocated in the memory.
Every time an object is created using the new() keyword, at least
one constructor is called.
Constructors can take parameters
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and
synchronized(non access specifier)
Constructors can be overloaded.
JAVA CONSTRUCTORS
14. // Create a MyClass
class public class MyClass
{
int x; // Create a instance variable
// Create a class constructor for the MyClass
MyClass()
{
x = 5; // Set the initial value for the instance variable x
}
public static void main(String[] args)
{
MyClass myObj = new MyClass(); // Create an object of class
MyClass (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
15. public class MyClass {
int x;
public MyClass(int y) {
x = y;
}
public static void main(String[] args) {
MyClass myObj = new MyClass(5);
System.out.println(myObj.x);
}
}
16. A command-line argument is an information that directly follows
the program's name on the command line when it is executed.
The command-line arguments are stored as strings in the String
array passed to main( ).
public class Echo {
public static void main (String[] args)
{
for (String s: args)
{
System.out.println(s);
}
}
}
COMMAND LINE ARGUMENTS
17. public class CommandLine {
public static void main(String[] args)
{
for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
Command line arguments are strings to parse it following
methods can be used:
ParseInt()
parseFloat()
parseDouble()
18. A variable provides us with named storage that our programs can
manipulate. Java provides three types of variables.
Class 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.
Instance variables − Instance variables are declared in a class,
but outside a method. When space is allocated for an object in
the heap, a slot for each instance variable value is created.
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.
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.
VARIABLES
19. A static variable is common to all the instances (or objects) of the class. i.e)only a
single copy of static variable is created and shared among all the instances of the
class. Memory allocation for such variables only happens once when the class is
loaded in the memory..
Static variable Syntax: static data_type variable_name
class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1 .increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count );//2
System.out.println("Obj2: count is="+obj2.count);
}
}
STATIC VARIABLE
20. public class VariableExample{
int myVariable;
static int data = 30;
public static void main(String args[]){
int a = 100;
VariableExample obj = new VariableExample();
System.out.println("Value of instance variable myVariable:
"+obj.myVariable);
System.out.println("Value of static variable data:
"+VariableExample.data);
System.out.println("Value of local variable a: "+a);
}
}
21. Whenever we declare variable as static, then at the class level a single
variable is created which is shared with the objects. Any change in that
static variable reflect to the other objects operations.
If we won’t initialize a static variable, then by default JVM will provide
a default value for static variable.
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable.
It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will
have detailed learning of these.
22. class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run(); // compile time error
}
}//end of class
23. If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
24. If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
25. The native keyword is applied to a method to indicate that the
method is implemented in native code using JNI (Java Native
Interface). native is a modifier applicable only for
methods and we can’t apply it anywhere else. The methods
which are implemented in C, C++ are called as native
methods or foreign methods.
The main objectives of native keyword are:
To improve performance of the system.
To achieve machine level/memory level communication.
To use already existing legacy non-java code.
NATIVE
26. Class Native
{
Public native void m();
}
Class Test
{
Public static void main(String[] args)
{
Native n = new Native();
n.m();
}
}
Important points about native keyword:
For native methods implementation is already available in old languages like C,
C++ and we are not responsible to provide implementation. Hence native method
declaration should end with ; (semi-colon).
We can’t declare native method as abstract.
The main advantage of native keyword is improvement in performance but the main
disadvantage of native keyword is that it breaks platform independent nature of
java.
27. The Java volatile keyword is used to mark a Java variable as "being
stored in main memory".
Every read of a volatile variable will be read from the computer's
main memory, and not from the CPU cache, and that every write to
a volatile variable will be written to main memory, and not just to
the CPU cache.
public class SharedObject
{
public volatile int counter = 0;
}
VOLATILE
28. Multi-threaded programs may often come to a situation where multiple threads try
to access the same resources and finally produce erroneous and unforeseen results.
So it needs to be made sure by some synchronization method that only one thread
can access the resource at a given point of time.
. Synchronized blocks in Java are marked with the synchronized keyword. A
synchronized block in Java is synchronized on some object. All synchronized blocks
synchronized on the same object can only have one thread executing inside them at
a time. All other threads attempting to enter the synchronized block are blocked
until the thread inside the synchronized block exits the block.
Following is the general form of a synchronized block:
// Only one thread can execute at a time.The code is said to be synchronized on
// the monitor object
synchronized(sync_object)
{
// Access shared variables and other
// shared resources
}
This synchronization is implemented in Java with a concept called monitors. Only
one thread can own a monitor at a given time. When a thread acquires a lock, it is
said to have entered the monitor. All other threads attempting to enter the locked
monitor will be suspended until the first thread exits the monitor.
SYNCHRONIZED