Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views10 pages

Java 2

This document provides an overview of Java classes, including definitions, object creation, and methods. It explains the structure of classes, instance variables, and the process of creating objects through declaration, instantiation, and initialization. Additionally, it covers constructors, method overloading, and provides examples to illustrate these concepts.

Uploaded by

Bhaskara Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Java 2

This document provides an overview of Java classes, including definitions, object creation, and methods. It explains the structure of classes, instance variables, and the process of creating objects through declaration, instantiation, and initialization. Additionally, it covers constructors, method overloading, and provides examples to illustrate these concepts.

Uploaded by

Bhaskara Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Java Programming(R19) Unit_II Java Programming(R19) Unit_II

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.

A Simple Class s.sid=1234;


Let’s begin our study of the class with a simple example. Here is a class called Student that s.sname=”Anand”;
defines three instance variables: sid, sname, and branch. Currently, Student does not contain any s.branch=”IT”;
methods.
Here is a complete program that uses the Student class: (StudentDemo.java)
class Student class Student
{ //instance variables {
int sid; int sid;
String sname; String branch; String sname;
} String branch;

MVR@Dept. Of CSE 1 MVR@Dept. Of CSE 2


Java Programming(R19) Unit_II Java Programming(R19) Unit_II

// This class declares an object of type Student.


class StudentDemo
{
public static void main(Stringargs[])
{
//declaring the object (Step 1) and instantiating (Step 2)object
Student std = newStudent();
2.3 Methods
// assign values to std’s instance variables (Step 3) Classes usually consist of two things:instance variables and methods. This is the general form of
s.sid=1234; a method:
s.sname=”Anand”;
s.branch=”IT”; type name(parameter-list)
{
// display student details // body of method
System.out.println(std.sid" "+std.sname+""+std.branch); }
}
} Here,
 type specifies the type of data returned by the method. This can be any valid data type,
When you compile this program, you will find that two .class files have been created, one for
including class types that youcreate.
Student and one for StudentDemo. The Javacompiler automatically puts each class into its own
 If the method does not return a value, its return type must bevoid.
.class file. It is not necessary for both the Student and the StudentDemo class to actually be in
the same sourcefile.  The name of the method is specified by name. This can be any legal identifier other than
To run this program, you must execute StudentDemo.class. When you do, you will see the those already used by other items within the currentscope.
following output:  The parameter-list is a sequence of type and identifier pairs separated bycommas.
 Parameters are essentially variables that receive the value of the arguments passed to the
1234 Anand IT method when it is called. If the method has no parameters, then the parameter list will be
empty.
As stated earlier, each object has its own copies of the instance variables. This means that if you  Methods that have a return type other than void return a value to the calling routine using
have two Student objects, each has its own copy of sid, sname, and branch. the following form of the returnstatement:

2.2.1 Assigning Object Reference Variables return value;


Object reference variables act differently than you might expect when an assignment takes place.
For example, what do you think the following fragment does? Here, value is the value returned.

Box b1 = new Box(); Adding a method to the Student class (Student.java)


Box b2 = b1; class Student
{
You might think that b2 is being assigned a reference to a copy of the object referred to byb1. intsid;
That is, you might think that b1 and b2 refer to separate and distinct objects. However,this would String sname;
be wrong. Instead, after this fragment executes, b1 and b2 will both refer to thesame object. The Stringbranch;
assignment of b1 to b2 did not allocate any memory or copy any part of theoriginal object. It show()
simply makes b2 refer to the same object as does b1. Thus, any changesmade to the object {
through b2 will affect the object to which b1 is referring, since they are thesameobject. System.out.println("Student ID"+sid);
This situation is depicted here: System.out.println("Student Name: "+sname);
System.out.println("Branch:"+branch);
}
}

Here the method name is "show( )". This methods contains some code fragment for displaying the

MVR@Dept. Of CSE 3 MVR@Dept. Of CSE 4


Java Programming(R19) Unit_II Java Programming(R19) Unit_II

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.

Returning a Value float percentage(int s1, int s2, ints3)


A method can also return the value of specified type. The method after computing the task returns {
the value to the caller of the method. sub1 = s1;
sub2 = s2;
class Student sub3 = s3;
{ return(sub1+sub2+sub3)/3;
int sid; }
String sname;
String branch; 2.3.2 MethodOverloading
int sub1, sub2, sub3; In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. In this case, the methods are said to be
public float percentage() overloaded, and the process is referred to as method overloading. Method overloading is one of
{ the ways that Java supports polymorphism.
return (sub1+ sub2+sub3)/3;
}  When an overloaded method is invoked, Java looks for a match between arguments of the
public void show() methods to determine which version of the overloaded method to actuallycall.
{  While overloaded methods may have different return types, the return type alone is
System.out.println("Student ID"+sid); insufficient to distinguish two versions of amethod.
System.out.println("Student Name: "+sname);  When Java encounters a call to an overloaded method, it simply executes the version of
System.out.println("Branch:"+branch); the method whose parameters match the arguments used in thecall.
}  When an overloaded method is invoked, Method overloading supports polymorphism
} becauseit isone way that Java implementsthe ―one interface, multiple methods‖paradigm.

class StudentDemo Here is a simple example that illustrates method overloading:


{ class Overload
public static void main(String args[]) {
{ void test()
Student std = new Student(); {
std.sid=1234;
std.sname=”Anand”;
MVR@Dept. Of CSE 5 MVR@Dept. Of CSE 6
Java Programming(R19) Unit_II Java Programming(R19) Unit_II

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

{ int sub1, sub2, sub3;


sid=id;
sname=name; Student() // This is the defaultconstructor
branch=br; {
sub1=s1; sid=501;
sub2=s2; sname= "Akhil";
sub3=s3; branch= "CSE";
} sub1=91;
public float percentage() sub2=92;
{ sub3=93;
return (sub1+ sub2+sub3)/3; }
} // This is a parameterized constructor forStudent
public void show() Student(int id, String name, String b, int s1 ,int s2, int s3 )
{ {
System.out.println("Student ID"+sid); sid=id;
System.out.println("Student Name: "+sname); sname=name;
System.out.println("Branch:"+branch); branch=br;
} sub1=s1;
} sub2=s2;
class StudentDemo sub3=s3;
{ }
public static void main(String args[]) public float percentage()
{ {
// declare, allocate, and initialize Student object return (sub1+ sub2+sub3)/3;
Student std = new Student(1234, "Anand","IT",89,90,91); }
float per=std.percentage(); //getting percentage public void show()
std.show(); {
System.out.println("Percentage:"+per); System.out.println("Student ID"+sid);
} System.out.println("Student Name: "+sname);
} System.out.println("Branch:"+branch);
}
Output }
Student ID: 1234 class OverloadCons
Student Name: Anand {
Branch: IT public static void main(String args[])
Percentage: 90 {
// create objects using the various constructors
2.4.1 Constructor Overloading Student std1 = new Student();
In Java, it is possible to define two or more class constructors that share the same name, as long as Student std2 = new Student(1234, "Anand","IT",89,90,91);
their parameter declarations are different. This is called constructor overloading.
float per1=std1.percentage(); //Calculating CSE student percentage
When an overloaded constructor is invoked, Java uses the type and/or number of arguments as its std1.show();
guide to determine which version of the overloaded constructor to actually call. Thus, overloaded System.out.println("Percentage:"+per1);
constructors must differ in the type and/or number of their parameters.
float per2=std2.percentage(); //Calculating IT student percentage
Example: OverloadCons.java std2.show();
class Student System.out.println("Percentage:"+per2);
{
int sid; }
String sname; }
String branch;
MVR@Dept. Of CSE 9 MVR@Dept. Of CSE 10
Java Programming(R19) Unit_II Java Programming(R19) Unit_II

Output // finalization code here


Student ID: 501 }
Student Name: Akhil
Branch: CSE Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
Percentage:92 outside its class.

Student ID: 1234 2.6 statickeyword


Student Name: Anand  There will be times when you will want to define a class member that will be used
Branch: IT independently of any object of that class. To create such a member, precede its declaration
Percentage:90 with the keywordstatic.
 The static keyword in java is used for memory managementmainly.
2.5 GarbageCollection  We can apply java static keyword with variables, methods, blocks and nestedclass.
Since objects are dynamically allocated by using the new operator, such objects are destroyed and  The static keyword belongs to the class than instance of theclass.
their memory released for later reallocation. Java handles de-allocation for you automatically. The  The static canbe:
technique that accomplishes this is called garbage collection. Java has its own set of algorithms to  variables (also known as classvariables)
do this as follow. There are Two Techniques:  methods (also known as classmethods)
1. Reference Counter
 block
2. Mark andSweep.
 nestedclass
In the Reference Counter technique, when an object is created along with it a reference counter is
The most common example of a static member is main(). main( ) is declared as static because it
maintained in the memory. When the object is referenced, the reference counter is incremented by
must be called before any objects exist.
one. If the control flow is moved from that object to some other object, then the counter value is
decremented by one. When the counter reaches to zero (0), then it's memory is reclaimed.
Java static variable
In the Mark and Sweep technique, all the objects that are in use are marked and are called live  If you declare any variable as static, it is known staticvariable.
objects and are moved to one end of the memory. This process we call it as compaction. The  The static variable can be used to refer the common property of all objects (that is not
memory occupied by remaining objects is reclaimed. After these objects are deleted from the unique for each object) e.g. company name of employees, college name of studentsetc.
memory, the live objects are placed in side by side location in the memory. This is called copying.  The static variable gets memory only once in class area at the time of classloading.

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

s3.display(); Let's understand the problem with example given below:


} class Student
} {
Output: int sid;
1211 Akshara VVIT String sname;
1222 Chaitanya VVIT float fee;
1233 Krishna VVIT Student(int sid, String sname, float fee)
{
Java static block this.sid=sid;
 It is used to initialize the static datamember. this.sname=sname;
 It is executed before main method at the time ofclassloading. this.fee=fee;
}
Note: Static blocks are executed first, even than the static methods. void show()
{
Example of static block System.out.println(sid+" "+sname+" "+fee);
class A }
{ }
static int i; class Test
static {
{ public static void main(String args[])
System.out.println("Static block is invoked"); {
i=10; Student std=new Student(1201,"Ankit",88000f);
} std.show();
public static void main(String args[])
{ }
System.out.println("Now in main"); }
System.out.println("i:ow"+A.i); Output
} 1201 Ankit88000.0
}
Output this: To invoke current class method
static block is invoked  You may invoke the method of the current class by using the thiskeyword.
Now in main
 If you don't use the this keyword, compiler automatically adds this keyword while
I:10
invoking themethod.
Let's see the example
class A
2.7 thiskeyword
{
 Sometimes a method will need to refer to the object that invoked it. To allow this, Java void m( )
defines thiskeyword. {
 this can be used inside any method to refer to the current object. i.e. this is always a System.out.println("hello m");
reference to the object on which the method was invoked. }
void n( )
Usage of java this keyword {
1. this can be used to refer current class instancevariable. System.out.println("hello n");
2. this can be used to invoke current classmethod. this.m();
3. this can be used to invoke current classconstructor. }
}
this: To refer current class instance variable class Test
 The this keyword can be used to refer current class instancevariable. {
 If there is ambiguity between the instance variables and parameters, this keyword resolves public static void main(String args[])
the problem ofambiguity. {
MVR@Dept. Of CSE 15 MVR@Dept. Of CSE 16
Java Programming(R19) Unit_II Java Programming(R19) Unit_II
class Java_Inner_class
A a=new A();
{
a.n();
//code
}
}
}
}
Output
hello n
Advantage of java inner classes
hello m
There are basically three advantages of inner classes in java. They are as follows:
1. Nested classes represent a special type of relationship that is it can access all the members
this: To invoke current class constructor (data members and methods) of outer class includingprivate.
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
2. Nested classes are used to develop more readable and maintainable code because it
the constructor. In other words, it is used for constructor chaining.
logically group classes and interfaces in one placeonly.
3. Code Optimization: It requires less code to write.
Calling default constructor from parameterized constructor:
Types of Nested classes
class A { There are two types of nested classes non-static and static nested classes. The non-static nested
A(){ classes are also known as inner classes.

} 1. Non-static nested class (innerclass)


a. Member inner class
System.out.println("hello a"); b. Anonymous innerclass
c. Local inner class
2. Static nestedclass
A(int x) {
this(); Type Description
System.out.println(x); Member Inner Class A class created within class and outside method.
} Anonymous Inner A class created for implementing interface or extending class. Its
} Class name is decided by the java compiler.
Local Inner Class A class created within method.
class Test{ Static Nested Class A static class created within class.
public static void main(String args[]) {
A a=new A(10); Static inner class
}  A static inner class is a nested class which is a static member of the outerclass.
}  It can be accessed without instantiating the outer class, using other static members.Just
like staticmembers.
Output  A static nested class does not have access to the instance variables and methods of the
hello a outerclass.
10  The syntax of static nested class is as follows −
classMyOuter
2.9 Nestedclasses
{
 A class defined within another class; such classes are known as nestedclasses. static class Mynested
 The scope of the nested class (inner class) is bounded by the scope of it’s enclosing class { }
(outerclass). }
 We use inner classes to logically group classes and interfaces in one place so that it can be
more readable andmaintainable.
 Additionally, it can access all the members of outer class including private data members
and methods.
Example: Outer.java
Syntax of Inner class public class Outer
class Java_Outer_class {
{ //inner static class
//code static class Nested_Demo
MVR@Dept. Of CSE 17 MVR@Dept. Of CSE 18
Java Programming(R19) Unit_II
{
public void my_method()
{
System.out.println("This is my nested class");
}
}
//body of outer class
public static void main(String args[])
{
//without creating the object of outer class
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}
}
Note:
1. static inner classes are rarely used inprograms.
2. If the static inner class is static method, we can directly call that method in the main()
function without creating the object. As follow:Outer.Nested_Demo.my_method();

Non-static inner class


 Creating an inner class is quite simple. You just need to write a class within aclass.
 An inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside theclass.

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

You might also like