Classes in Java
Classes in Java
Rajam Naidu
What is a Class?
type methodName(parameter-list) {
body of method ;
return value;
}
Methods – 1 cont
class Student { System.out.println("Student ID“ + sid);
• In the Mark and Sweep technique, all the objects that are in use
are marked and are called live objects and are moved to one
end of the memory. This process we call it as compaction. The
memory occupied by remaining objects is reclaimed. After
these objects are deleted from the memory, the live objects are
placed in side by side location in the memory. This is called
copying.
The finalize() Method
• Sometimes an object will need to perform some action when it is
destroyed. For example, if an object is holding some non-Java
resource such as a file handle or character font, then you might want
to make sure these resources are freed before an object is
destroyed. To handle such situations, Java provides a mechanism
called finalization. By using finalization, you can define specific
actions that will occur when an object is just about to be reclaimed
by the garbage collector.
Static Keyword - 1
• There will be times when you will want to define a class
member that will be used independently of any object of that
class. To create such a member, precede its declaration with
the keyword static.
• The static keyword in java is used for memory management
mainly.
• We can apply java static keyword with variables, methods,
blocks and nested class.
• The static keyword belongs to the class than instance of the
class.
Static Keyword - 2
• The static can be:
• variables (also known as class variables)
• methods (also known as class methods)
• block
• nested class
• The most common example of a static member is main().
• main( ) is declared as static because it must be called before
any objects exist.
Java static variable
• The static variable gets memory only once in class area at the
time of class loading.
Static Variable Usage
class Student {
int rollno;
String name;
Static String college=“Rishi IT"; }
Counter using static variable
As we have mentioned above, System.out.println(count);
static variable will get the memory }
only once, if any object changes
the value of the static variable, it public static void main(String
will retain its value. args[]) {
class Counter { Counter c1=new Counter();
Counter c2=new Counter();
//will get memory only once and Counter c3=new Counter();
retain its value
}
static int count=0;
}
Counter( ) {
count++;
Java static method - 1
• If you apply static keyword with any method, it is known as
static method.
• A static method belongs to the class rather than object of a
class.
• A static method can be invoked without the need for creating an
instance of a class.
• Static method can access static data member and can change
the value of it.
Java static method - 2
• There are three main restrictions for the static method. They
are:
1. They cannot call non-static methods.