2. 4.1 Defining classes
• What is class?
A class describes the data and behavior associated
with instances of that class.
• When class is instantiated, an object is created.
• A class can be defined as follows:
class First
{
Body of the class
}
• Every class defined in Java is a child of the Object class
3. Creating instance and class variable
• A class usually contains variables and methods. Java allows
three types of variables. That is,
1. Instance variable.
2. Constance
3. Class variables.
Instance variables
That are declared and defined in almost the same
way as local variables, the main difference being their
location in the class definition. Variables are considered
instance variables, if they are declared outside a method
definition. It is like a global declaration.
4. Contd..
Constants
A constant variable or constant is a variable whose
value never change. To declare a constant, the keyword final
is used.
Example: final float pi=3.14;
Class variables
Class variables are global to a class and to all
instances of that class. Class variables are used for
communication between objects within the same class. The
static keyword is used in the class declaration to declare a
class variable.
Example: static int sum;
5. 4.1.2 Defining methods
• In java method definition consists four fundamental parts.
That is,
The name of the method
The object type
The list of the parameters
Body of the method
• The first three parts of the method definition are referred
to as method declaration or method signature.
• The process of having methods with the same name but
with different arguments is referred as method
overloading
6. Method definition
• return_type method_name(type1 arg1,type2 arg2,……)
{
body of the method
}
• Example:
int[] method1(int a1,int a2) int method1(int a1,int a2)[]
{ {
//body of the method //body of the method
} }
• If return type is real(that is not void ), a value should be
returned explicitly in the body of method. Java provides
the keyword return.
7. Example program
Class main
{
Public static void main(String[] args)
{
System.out.println(“Method definition”);
myMethod(); //method declaration
System.out.println(“Method executed”);
}
Private static void myMethod()
{
System.out.println(“Method definition”);
}
}
8. 4.1.3 Knowing this
• Programmers sometimes refer to the current object
within the body of the method. By referring to the current
object programmers would be able to access the instance
variable of that object.
• Example:
t=this.x; // the x instance variable for this object
this.myMethod(this) //calls the myMethod, defined
in this class and passed it to the current object.
return this; //returns the current object
9. Example program
Public class circle
{
int x,y,r;
public circle(int x,int y,int r)
{
this.x=x;
this.y=y;
this.r=r;
This.display();
}
Void display()
{
SOP(“value of x is”+x);
SOP(“value of y is”+y);
SOP(“value of r is”+r);
}
Psvm(String[] args)
{
Sop(“using this keyword”);
Circle ob=new circle(10,20,10);
}
}
OUTPUT:
Using this keyword
value of x is 10
value of y is 20
value of r is 10
10. 4.1.4 Variable scope and method
definitions
• The scope of a variable specifies the region of the source
program where that variable is known, accessible and can
be used.
• Local variable can be only within the block in which they
are defined. The scope of instance variables covers entire
class.
• Variables must be declared before usage within a scope.
Variables that are declared in an outer scope can also be
used in an inner scope.
11. Example program
Class scope
{
Static in var=10;
Scope()
{
SOP(“outer scope”+var);
}
PSVM(String args[])
{
Int var=25;
Scope sc=new scope();
SOP(“current scope”+var);
}
}
OUTPUT:
Outer scope 10
Current scope 25
12. Passing arguments to methods
• There are mainly two ways of passing arguments to methods:
1. Pass by value
2. Pass by reference
• Java directly supports passing by value; however, passing by
reference will be accessible through reference objects.
• Pass by value
When the arguments are passed using the pass by value
mechanism only a copy of the variable are passed which has the
scope within the method which receives the copy of these
variable.
• Pass by reference
When parameters are passed to the methods, the calling
method returns the changed value of the variables to the called
method. The call by reference mechanism is not used by Java for
passing information. It only pass arguments not values.
13. Example program
Pass by value
Class main
{
PSVM(String[] args)
{
int x=5;
change(x);
SOP(“X is”+x);
}
Public static void change(int x)
{
X=10
}
}
OUTPUT
X is 5
14. 4.1.6 Class methods
• Java has two methods. That is,
1. Class methods
2. Instance methods
• Class method
It is method which are declared as static. The
method can be called without creating an instance of the
class.
• Instance method
Instance method operate specific instances of
classes. It is created by using new keyword.
15. 4.1.7 Overloading methods
• The process of defining methods with same name but with
different functionality is termed method overloading.
• When a method in an object is called, Java verifies its
name and argument type so that appropriate method
definition is executed.
• Java differentiates overloaded methods based on the
number and type of parameters and not on the return
types of the method.
16. Example program
Class overload
{
public static void First()
{
SOP(“without args”);
}
public static void First(int
a,int b)
{
SOP(a+b);
}
PSVM(String[] args)
{
First();
First(10,20);
}
}
OUTPUT
Without args
30
17. 4.1.8 Constructor methods
• Constructor methods initialize new objects when they are
created. They are automatically when a new object is created.
Memory is allocated for the new object.
Instance variables of the object are initialized, either to their
initial values or to default values.
A constructor method is invoked with different argument lists.
Based on the number of parameters and their data types, the
corresponding constructor will be invoked.
• Basic constructors
constructors looks like a regular methods with two basic
differences. That is,
i. Constructors always have the same name as the class
ii. Constructors do not have a return type
18. Program to initialize student details using
parameterized constructor
class Student
{
int rollNo;
String name;
Student (int r, String n)
{
rollNo = r;
name = n;
}
void display ()
{
System.out.println ("Student Roll
Number is: " + rollNo);
System.out.println ("Student
Name is: " + name);
}
}
class StudentDemo
{
public static void main(String args[])
{
Student s1 = new Student
(101,“Suresh”);
System.out.println (“s1 objectcontains:“
);
s1.display ();
Student s2 = new Student (102,
“Ramesh”);
System.out.println (“s2 object
contains:“ );
s2.display ();
}
}
19.
20. Calling another constructor
• A constructor defined within the current class can be
called using the keyword this.
• The syntax would be as follows,
this(arg1,arg2,arg3…);
21. Example program
Class stud
{
Int id;
String name;
Int age;
Stud(int I,String n)
{
Id=I;
Name=n;
}
Stud(int i,String n,int a)
Id=I;
Name=n;
Age =a;
}
Void display()
{
SOP(id+””+name+””+age);
}
PSVM(String[] args)
{
Stud s1=new stud(111,”LEO”);
Stud s2=new stud(222,”JOE”,24);
S1.display();
S2.display();
}
}
OUTPUT
111,LEO,0
222,JOE,24
22. 4.1.9 Inheritance,Polymorphism, and
Abstract classes
• Inheritance
The term inheritance refers to the fact that one class can
inherit a part or all of it’s structure and behavior from another class.
The class that inherits the property from another class is termed
child class.
In inheritance extend keyword is used.
Syntax
class B extends A
{
//additions and modifications of class A
}
Class A
(super class)
Class B
(sub class)
23. Extending existing classes
• The existing class can be extened to create sub-class. The
syntax for this is given below:
class subclass_name extends existing_class_name
{
//changes and additions.
}
Example:
24. Example program
Class doctor
{
Void doctor_details()
{
SOP(“Doctor details”);
}
}
Class surgeon extends doctor
{
Void surgeon_details()
{
SOP(“Surgeon details..”);
}
}
Public class hospital
{
PSVM(String[] args)
{
Surgeon s=new surgeon();
s.doctor_details();
s.surgeon_details();
}
}
The process of sub class
becomes a parent class of a
different class is termed
multilevel inheritance
Example: Lab program
25. Overriding methods
• Overriding a method
involves defining a method
in a sub classs that has the
same signature as some
method in a super class.
• When that method is
called, the method in the
sub-class is found and
executed instead of the
one in the super-class
• Use:
to replace the definition of
original method completely.
to add new functionality to
the original method.
• Example
Class overrid {
Public void display() {
SOP(“Overrid method”); }
Public class override extends
override {
Public void display() {
SOP(“override overrid class”); }
PSVM(String args[])
{
Override o=new override();
o.display; } }
26. Overriding constructor
• Ensures that the initialization of inherited parts of the objects
takes place similar to the way the super class initializes its
object.
• It is used to define sub class method definition in the super
class.
• Syntax:
super.methodname(arguments-name)
• Example:
super.printsuperclass();
• Rules for super() keyword
1.The first calling method must be super() in the
constructors definition.
2.super() is used to call a constructor method with the
appropriate arguments from the immediate super class.
3.To use super() in the constructor of sub class,
constructor with the same signature must exist in the super class.
27. 4.1.11 Finalizer method
• Finalizer method are almost opposite of constructor
methods.
• A constructor method is used to initialize an object, while
finalizer method are called just before the object is
garbage collected and its memory reclaimed.
• Keyword-finalize()
• Syntax
protected void finalize() throws Throwable
{
super.finalize();
}
28. 4.2 Modifiers
• Modifiers are keywords used to define the scope and
behavior of classes, methods and variable in java.
• A variety of modifiers:
Access modifiers
(Private,public,proteced,packages)
Static
Abstract
Final
Synchronized and
volatile(thread)
native
29. Access Specifiers
• An access Specifiers is a key word that represents how to
access a member of a class. There are four access
Specifiers in java.
• The four Ps of protection:
• private: private members of a class are not available
outside the class.
• public: public members of a class are available anywhere
outside the class.
• protected: protected members are available outside
inherited classes.
• packages: methods and variables with packages
protection are visible to all other classes in the same
package but not outside that package
30. Different types of protection
Visibility public protected package private
From the same class yes Yes Yes yes
From any class in the
same package
yes Yes yes No
From any class outside
the package
yes No No no
From a sub class in the
same package
Yes Yes Yes no
From a sub class outside
the same package
Yes Yes No no
31. Method protection and inheritance
• Method declared public in a super class must be also be
public in all sub class.
• Methods declared protected in a super class must either
be protected or public in sub classes but they cannot be
private
• Methods declared private are not inherited and therefore
this rule does not apply.
• Methods for which the protection type has not been
declared can take more private protection types in sub
classes.
32. Class variables and methods(Static)
• To create class variable and methods, include the word
static in front of the method’s name.
• The modifier static typically comes after any protection
modifiers
33. Finalizing classes , methods and
variables
• The final is used to finalize classes methods and variables.
Finalizing a thing effectively ‘freeze’ the implementation or
value a thing.
• Uses:
When the modifier final is applied to a class, it means that
the class cannot be inherited
When final is applied to a variable, it means that the
variables is constant.
When final is applied to a method in a class, it means that
the method cannot be overridden in the sub classes.
34. Finalizing class
• It is added after protection modifiers such as private or
public.
• Syntax:
public final class class_name
{
….
}
• A class is declared as a final for followings:
1.To prevent inheritance
2.For better efficiency.
35. Finalizing variables
• The value of a finalized variable cannot be changed. It is
then effectively a constant.
• Declaration:
public class finalclass2
{
public static final int cons=100;
}
• Local variable cannot be declared final.
36. Finalizing methods
• Methods that cannot be overridden are known as a
finalized methods the implementations of final methods
cannot be redefined in sub classes.
• Syntax:
public class finalmethod
{
public final void one()
{
…
}
}
37. Abstract classes and methods
• Abstract class:
abstract classes whose sole purpose is to provide
common information for sub classes. abstract classes can have no
instances.
• Abstract methods:
abstract methods are with signature, but no
implementations. The sub classes of the class that contains that
abstract method must provide its actual implementations
• Syntax
public abstract class abs
{
…
}
38. example
Abstract class bike
{
Abstract void run();
}
class honda extends bike
{
Void run()
{
SOP(“running safely”);
}
PSVM
Bike b=new honda();
B.run();
}
}
Output:
Running safely
41. Syntax
try
{
//java statements capable of throwing exceptions
}
catch(Exception1_e)
{
//java statements capable of throwing exceptions_1
}
finally
{
//cleanup code or exit code
}
42. Try block
• The statement in a program that may raise exceptions are
placed within a try block.
• A try block is a group of Java statements enclosed within
the braces{}, which are to checked and unchecked
exceptions.
• Keyword – try
• A try block should have one or more catch block or one
finally block or both.
43. Catch block
• A catch block is a group of Java statements enclosed in
braces {} which are used to handle specific exception that
has been thrown.
• Catch blocks should placed after the try block
• Keyword- catch with single parentheses()
• Example:
catch(Exception e)
44. Finally block
• The final step of exception handling is providing a
mechanism for cleaning up the program before the
control is passed to different part of the program.
• Keyword- finally
• If there is no exception catch block is executed finally block
will be executed.
45. Example program
Public class divide
{
public static void main(String[]
args)
{
System.out.println(“Program
start”);
int a,b,c;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a/b;
System.out.println(a+”/”+b+”=“+c
);
}
Catch(Exception e)
{
System.out.println(e);
}
Finally
{
System.out.println(“Finally
executed”);
}
System.out.println(“Program
End”);
}
}
46. Multithreading
A thread is a single sequential flow
of control within a program
A thread can be defined as a
process in execution within a
program.
47. Thread Life cycle
sleep() notify() run method over
Start() wait() resume()
suspend() sleep time over
stop()
stop()
Newborn
runnable running
dead
blocked
48. Contd..
• A thread is always in one of five states: newborn,
runnable, running, dead and blocked.
• 1.The newborn state
when a thread is called, it is in newborn state, that
is, when it has been created and is not yet running. In other
words, a start() method has been invoked on this thread.
• 2.The runnable state
A thread in the runnable state is ready for execution
but is not being executed currently. Once a thread is in the
runnable state, it gets all resource of the system and moves
on to the running state.
49. Contd..
• 3.The running state
after the runnable state, if the thread gets CPU access, it
moves into the running state. The thread will be in the running
state unless one of the following things occur:
It dies(run() that is run method exits.)
It gets b;ocked to the input/output for some reason.
It calls sleep()
It calls wait()
It calls yield()
It is preempted by a thread of higher priority
Its quantum(time slice) expires
50. Contd..
• 4. The dead state
A thread goes into the dead state in two ways:
1.If its run() method exits.
2.A stop() method invoked.
• 5. The blocked state
A thread can enters the blocked state when one of the
following five conditions occur:
Wen sleep() is called
When suspend() is called
When wait() is called
The thread calls an operation
The thread is waiting for monitor.
51. Contd..
• 6.Manipulating threads
• It includes the sleep(), suspend(), resume(), wait(), notify(),
notifyall() and yield().
Sleep()- to block the thread for sometime and free the CPU.
Suspend() – stop the thread temporarily.
resume() – to restart it at the point at which it is halted.
Wait() – particular object wait was called.
Notify() – issued another thread is associated with the object
Notifyall() – receive and issued another thread is associated
with the object
Yield() – first thread allows other thread to execute
52. Applets
Applets are dynamic and
interactive programs. Applets are
usually small in size and facilitate
event-driven applications that can
be transported over the web.
54. Applet methods
• Init()
*The first method to be called.
*Runs once at the time of initilization before the
applet starts. That is it is called when the applet is first
loaded and created by the browser.
• Start()
Runs whenever the applet become visible. That is, it
is called when an applet start or restarts after being
stopped.
• Stop()
Runs whenever the applet become invisible. That is it is
called when the applet leaves the web page.
55. Contd..
• Destroy()
Runs only once when the browser exits. The applet
will be removed from the memory.
• Paint()
Runs whenever the applet needs to be drawn or
displayed.
• Repaint()
Runs if the applet wants to be repainted again.