Java 2
Java 2
2.1 What isclass? As stated, a class defines new data type. The new data type in this example is, Box. This defines
A class is a group of objects that share the same properties and methods. It is a template or the template, but does not actually create object.
blueprint from which objects are created. The objects are the instances of class. Because an object
is an instance of a class. A class is used to define new type of the data. Once defined, this new Note: By convention the First letter of every word of the class name starts with Capital letter, but
type can be used to create objects of its type. The class is the logical entity and the object is the notcompul y. For example student is written as“Student”The letter ofthe
logical and physicalentity. method name begins with small and remaining first letter of every word starts with Capital
letter, butnotcompul y. For exampleboxVolume(
The general form of the class
A class is declared by use of the class keyword. A simplified general form of a class definition is 2.2 Creating theObject
shown here: There are three steps when creating an object from a class:
class classname
{ Declaration: A variable declaration with a variable name with an object type.
type instance-variable1; Instantiation: The 'new' key word is used to create the object.
type instance-variable2; Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the
……….. new object.
….…….
type instance-variableN; Step 1:
Student s;
type method1(parameterlist)
{ Effect: s
null
//body of the method1
} Declares the class variable. Here the class variable contains the value null. An attempt to access
type method2(parameterlist) the object at this point will lead to Compile-Time error.
{
//body of the method2 Step 2:
} Student s=new Student();
……..
……. Here new is the keyword used to create the object. The object name is s. The new operator
type methodN(parameterlist) allocates the memory for the object, that means for all instance variables inside the object,
{ memory isallocated.
//body of the methodN
sid
} Effect:s sname
}
branch
The data or variables, defined within the class are called, instancevariables. Student Object
The methods also contain thecode. Step 3:
The methods and instance variables collectively called asmembers. There are many ways to initialize the object. The object contains the instance variable.
Variable declared within the methods are called localvariables. The variable can be assigned values with reference of the object.
Here the method name is "show( )". This methods contains some code fragment for displaying the
student details. This method can be accessed using the object as in the following code: std.branch=”IT”;
std.sub1=89;
StudentDemo.java std.sub2=90;
class StudentDemo std.sub3=91;
{ float per=std.percentage(); //calling the method
public static void main(String args[]) std.show();
{ System.out.println("Percentage:"+per);
Student std = new Student(); }
s.sid=1234; }
s.sname=”Anand”; Output
s.branch=”IT”; Student ID: 1234
std.show(); // display studentdetails Student Name: Anand
Branch: IT
} Percentage: 90
}
2.3.1 Adding a method that takes theparameters
Output We can also pass arguments to the method through the object. The parameters separated with
Student ID: 1234 comma operator. The values of the actual parameters are copied to the formal parameters in the
Student Name: Anand method. The computation is carried with formal arguments, the result is returned to the caller of
Branch:IT the method, if the type ismentioned.
System.out.println("No parameters"); {
} sid=1234;
// Overload test for one integer parameter. sname=”Anand”;
void test(int a) branch=”IT”;
{ sub1=89;
System.out.println("a: " + a); sub2=90;
} sub3=91;
} }
class OverloadDemo public float percentage()
{ {
public static void main(String args[]) return (sub1+ sub2+sub3)/3;
{ }
Overload ol = new Overload; public void show()
double result; {
// call all versions of test() System.out.println("Student ID"+sid);
ob.test(); System.out.println("Student Name: "+sname);
ob.test(10); System.out.println("Branch:"+branch);
} }
} }
Output class StudentDemo
No parameters {
a: 10 public static void main(Stringargs[])
{
The test() method is overloaded two times, first version takes no arguments, second version // declare, allocate, and initialize Student object
takes oneargument. Student std = newStudent();
float per=std.percentage(); //calling the method
2.4 Constructors std.show();
A constructor is a special member function used for automatic initialization of an object. System.out.println("Percentage:"+per);
Whenever an object is created, the constructor is called automatically. Constructors can be }
overloaded. }
Output
Characteristics Student ID: 1234
Constructors have the same name as that of the class they belongsto. Student Name: Anand
They automatically execute whenever an object iscreated. Branch: IT
Constructors will not have any return type evenvoid. Percentage: 90
Constructors will not return anyvalues.
The main function of constructor is to initialize objects and allocation of memory tothe Parameterized Constructors
objects. It may be necessary to initialize the various data members of different objects with different
Constructors can beoverloaded. values when they are created. This is achieved by passing arguments to the constructor function
when the objects are created. The constructors that can take arguments are called parameterized
A constructor without any arguments is called as defaultconstructor.
constructors.
Example
/* Here, Student uses a parameterized constructor to initialize the details ofastudent. */
class Student
class Student
{
int sid; {
String sname; int sid;
String branch; String sname;
int sub1, sub2, sub3; String branch;
int sub1, sub2, sub3;
Student() // This is the constructor forStudent // This is a parameterized constructor forStudent
Student(int id, String name, String b, int s1 ,int s2, int s3 )
MVR@Dept. Of CSE 7 MVR@Dept. Of CSE 8
Java Programming(R19) Unit_II Java Programming(R19) Unit_II
It works like this: when no references to an object exist, that object is assumed to be no longer Advantage of static variable
needed, and the memory occupied by the object can be reclaimed. Garbage collection only occurs It makes your program memory efficient (i.e it savesmemory).
during the execution of your program. The main job of this is to release memory for the purpose
ofreallocation. Example:
class Student
The finalize( ) Method {
Sometimes an object will need to perform some action when it is destroyed. For example, if an int rollno;
object is holding some non-Java resource such as a file handle or character font, then you might String name;
want to make sure these resources are freed before an object is destroyed. To handle such String college="VVIT";
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. Suppose there are 3000 students in my college, now all instance data members will get memory
each time when object is created. All student have its unique rollno and name so instance data
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that member is good. Here, college refers to the common property of all objects. If we make it static,
method whenever it is about to recycle an object of that class. Inside the finalize( ) method, you this field will get memory only once. Java static property is shared to all objects.
will specify those actions that must be performed before an object is destroyed. The garbage
collector runs periodically, checking for objects that are no longer referenced by any running state class Student
or indirectly through other referencedobjects {
The finalize( ) method has this generalform: int rollno;
String name;
protected void finalize( ) static String college ="VVIT";
{
MVR@Dept. Of CSE 11 MVR@Dept. Of CSE 12
Java Programming(R19) Unit_II Java Programming(R19) Unit_II
Student(int r, String n)
{ There are three main restrictions for the static method. They are:
rollno = r; 1. They cannot call non-staticmethods.
name = n; 2. They cannot access non-staticdata.
} 3. They cannot refer to this or super in anyway.
void show( ) Example of static method that calculates cube of a given number.
{ class Calculate
System.out.println(rollno+" "+name+" "+college); {
} static int cube(int x)
public static void main(String args[]) {
{ return x*x*x;
Student s1 = new Student(1201,"Ajith"); }
Student s2 = new Student8(1202,"Alekhya"); public static void main(String args[])
s1.display(); {
s2.display(); int result = Calculate.cube(5);
} System.out.println(result);
} }
}
Output:
1201 Ajith VVIT Output: 125
1202 Alekhya VVIT
Another example of static method that access static data member and can change the value
Program of counter by static variable of it
As we have mentioned above, static variable will get the memory only once, if any object changes class Student
the value of the static variable, it will retain its value. {
int rollno;
class Counter String name;
{ static String college= "BBCCIT"; //static variable
staticint count=0; //will get memory only once and retain its value staticvoidchange() //static method
Counter() {
{ college = "VVIT";
count++; }
System.out.println(count);
} Student(int r, String n)
public static void main(String args[]) {
{ rollno = r;
Counter c1=new Counter(); name = n;
Counter c2=new Counter(); }
Counter c3=new Counter(); void display ()
} {
} System.out.println(rollno+" "+name+" "+college);
}
Output:1 2 3 public static void main(String args[])
{
Java static method Student.change();
If you apply static keyword with any method, it is known as staticmethod. Student s1 = new Student (1211,"Akshara");
A static method belongs to the class rather than object of aclass. Student s2 = new Student (1222,"Chaitanya");
A static method can be invoked without the need for creating an instance of aclass. Student s3 = new Student (1233,"Krishna");
Static method can access static data member and can change the value ofit. s1.display();
s2.display();
MVR@Dept. Of CSE 13 MVR@Dept. Of CSE 14
Java Programming(R19) Unit_II Java Programming(R19) Unit_II
Following is the program to create an inner class and access it. In the given example, we make the
inner class private and access the class through a method.
Example
public classOuter
{
int outer_x=100;
voidtest()
{
//creating the object of Inner class
Inner inn=new Inner();
inn.disp();
}
//inner non-static class
private class Inner
{
public void disp()
{
System.out.println("The value of x is:"+outer_x);
}
}
public static void main(String args[])
{
//creating the out class object
Outer2 out=new Outer2();
out.test();
}
}
MVR@Dept. Of CSE 19