Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

UNIT II - CLASSES AND METHODS

Introducing Classes-Class fundamentals - Declaring Objects - Assigning object


reference variables. Introducing method –Constructors - The this Keyword-Garbage
Collection - Finalize() method-Overloading methods-Using objects as parameters -
Argument Passing - Returning Objects - Recursion –static and final keyword -
Nested and Inner Classes - String Class - Command Line arguments.

Class
In Java everything is encapsulated under classes. Class can be defined as a
template/blueprint that describes the behaviors/states of a particular
entity. A class defines new data type. Once defined, this new type can be used
to create object of that type. Object is an instance of class. You may also call
it as physical existence of a logical template class
A class is declared using class keyword. A class contains both data and code
that operate on that data. The data or variables defined within a class are
called instance variables and the code that operated on this data is known as
methods
The General Form of a Class
class classname [ extends baseclass implements interface1, interface2 ]
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}

type methodname2(parameter-list)
{
// body of method
}

// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Rules for Java Class
 A Class can have only public or default(no modifier) access specifier
 It can be either abstract, final or concrete(normal class)
 It must have the class keyword, and class must be followed by a legal
identifier
 It may optionally extend one parent class. By default, it will extend
java.lang.Object
 It may optionally implement any number of comma-separated interfaces
 The class‟s variables and methods are declared within a set of curly
braces {}
 Each .java source file may contain only one public class.
 Finally the source file name must match the public class name and it
must have a .java suffix
Object
Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors -wagging, barking, eating. An object is an instance
of a class.
There are three steps when creating an object from a class:
 Declaration: A variable declaration with a variable name and object type.
 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor.
This call initializes the new object.
The general syntax for declaring object
classname ref_var;
ref_var = new classname ( );
Here, ref_var is a variable of the class type being created. The classname is the
name of the class that is being instantiated. After the first line executes, ref_var
contains the value null, which indicates that it does not yet point to an actual
object. The next line allocates an actual object and assigns a reference to it to
ref_var.
The new operator dynamically allocates memory for an object. The class name
followed by parentheses specifies the constructer for the class. A constructer
defines what occurs when an object of a class is created.
Example for Class and Object
class Pencil
{
private String color = "red";

public void setColor (String newColor) {


color = newColor;
}
public String getColor(){
return color;
}
public static void main(String[] args)
{
Pencil p = new Pencil(); //Object creation
p.setColor("red");
System.out.println("Pencil color is "+p.getColor()):
} }
Assigning object reference variables
When you assign one object reference variable to another object reference
variable, you are not creating a copy of the object; you are only making a copy
of the reference.
Methods
The general form of a method is
type methodname (parameter-list) {
// body of method
}
Every method should specify the type of data to be returned. This can be any
valid type, including class types that you create. If the method does not return
a value, its return type must be void. The name of the method can be any valid
identifier. The parameter-list is a sequence of type and identifier pairs
separated by commas. Parameters are variables that receive the value of the
arguments passed to the method when it is called.

Methods that have a return type other than void return a value to the calling
routine using the following form of the return statement:
return value;
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an
instance variable the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor ();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName()
Constructors
 A constructor is a special method that is used to initialize an object upon
creation.
 They have the same name as class name in which it resides
 Constructors have zero or more parameters
 A constructor does not have any return type, not even void. Implicit
return type is class type itself
 Constructor in java cannot be abstract, static, final or synchronized.
These modifiers are not allowed for constructors
 Constructors cannot be inherited
 Constructors can be overloaded (i.e) A class can have more than one
constructors
 Every class has a constructor. If you don‟t explicitly declare a constructor
for a java class, the compiler builds a default constructor for that class.
Types of Constructors
 Default constructor - Constructor with no argument is called default
constructor.
Example
class Point
{
int x, y;
Point( ){ //Default Constructor
x = y = 0;
}

}
 Parameterized Constructors - Constructor with parameter is called
parameterized constructor.
Example
class Point
{
int x, y;
Point(int i,int j){ //Parameterized Constructor
x = i;
y = j;
}

}
Constructor Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors
are differentiated on the basis of their type of parameters or number of
parameters. Constructor overloading is not much different than method
overloading
Example
class Point
{
private int x,y;
Point() //default constructor
{
x = y = 0;
}
Point(int i, int j) //parameterized constructor with 2 argument
{
x = i;
y = j;
}
public void display()
{
System.out.println(x+" , "+y);
}
public static void main(String[] args)
{
Point p1 = new Point();
Point p2 = new Point(10,20);
p1.display();
p2.display();
}
}
Output
0,0
10 , 20
this keyword
The this keyword in java can be used inside any method to refer to the current
object (i.e.) „this’ is always a reference to the object on which the method was
invoked.
Instance variable hiding
When a local variable has the same name as an instance variable, the local
variable hides the instance variable. As the keyword ‘this’ lets you refer
directly to the object, you can use it to resolve any name space collisions that
might occur between instance variables and local variables.
Example

class Point
{
int x, y;
Point(int x,int y)
{
this.x = x; //this.x refers to instance variable x
this.y = y;
}

}
Garbage Collection
In Java, destruction of object from memory is done automatically by the JVM.
When there is no reference to an object then that object is assumed to be no
longer needed and memory occupied by the object is released. This technique is
known as Garbage Collection.
Advantage of Garbage Collection
 Programmer doesn‟t need to worry about dereferencing an object
 Increases Memory efficiency and decreases the chance of memory leak
 It is done automatically by JVM
finalize() Method
Sometimes an object will need to perform some clean up task (such as closing
an open connection or releasing any resources held) before it is destroyed. By
using finalization, we can define specific actions to occur, just before it is
garbage collected.
To add a finalizer to a class, simply define finalize() method as follow
protected void finalize()
{
//code
}
Method Overloading
If two or more method in a class has same name but different parameter list, it
is known as method overloading. Java implements static polymorphism using
method overloading. Method overloading can be done by changing number of
argument or by changing the data type of argument. If two or more methods
have same name and same parameter list, but differs in return type are not
said to be overloaded method.
When an overloaded method is called, java look for match between the
arguments to call the method and method‟s parameters. This match need not
always be exact. Sometimes when exact match is not found, Java automatic
type conversion plays a vital role.
Example
class Calculate
{
public void sum(int a, int b){
System.out.println("Sum = "+(a+b));
}
public void sum(double a, double b){
System.out.println("Sum = "+(a+b));
}
public void sum(int a, int b, int c){
System.out.println("Sum = "+(a+b+c));
}
public static void main(String[] args){
Calculate c = new Calculate();
c.sum(3,4); //sum(int a, int b) is called
c.sum(1,2,3); //sum(int a, int b, int c) is called
c.sum(10.23,23.3); // sum(double a, double b) is called
}
}
Output
Sum = 7
Sum = 6
Sum = 33.53
Argument passing
There are two ways that java can pass an argument to a method.
 Call by value
 This method copies the value of an argument into formal parameter of
the method. Changes made to the parameter of the method have no
effect on the argument used to call it.
 In Java, when you pass a simple type to a method, it is passed by
value.
 Call by Reference
 In this method, a reference to an argument (not the value of the
argument) is passed to the parameter. Changes made to the
parameter will affect the argument used to call the method.
 In java, objects are always passed by reference.
Example
package javalab;
class Point
{
int x,y;
Point(int i,int j)
{
x=i;
y=j;
}
}
public class Test {
static void increment(int a) //Call by Value
{
a++;
}
static void increment(Point p) //Call by reference
{
p.x++;
p.y++;
}
public static void main(String[] args)
{
Point p = new Point(10,20);
int a = 5;
System.out.println("Before Method Call");
System.out.println("a = "+a);
System.out.println("p.x = "+p.x);
System.out.println("p.y = "+p.y);
increment(a);
increment(p);
System.out.println("After Method Call");
System.out.println("a = "+a);
System.out.println("p.x = "+p.x);
System.out.println("p.y = "+p.y);

}
}
Using objects as parameters and returning objects
A method can have any type of data, including class types that you create, as
argument and can return any type including objects.
Example
package javalab;
public class Point {
int x,y;
Point()
{
x = y = 0;
}
Point(int i,int j)
{
x = i;
y = j;
}
static Point addPoint(Point p1, Point p2 ) //Object as argument and return value
{
Point p3 = new Point();
p3.x = p1.x+p2.x;
p3.y = p1.y+p2.y;
return p3;
}
void display()
{
System.out.println(x+" , "+y);
}
public static void main(String[] args)
{
Point p1 = new Point(10,20);
Point p2 = new Point(1,2);
Point p3 = addPoint(p1, p2);
p1.display();
p2.display();
p3.display();

}
}
Output
10 , 20
1,2
11 , 22
Recursion
Recursion is the process of defining something in terms of itself. In java
programming, recursion is the attribute that allows a method to call itself. A
method that calls itself is said to be recursive.
Example
package javalab;
public class FactNo {
static int Fact(int n) //Recursive Function
{
if(n <=1)
return 1;
else
return n*Fact(n-1);
}
public static void main(String[] args)
{
System.out.println(Fact(5));
}
}
Output
120
Static Fields and Methods
We may apply static keyword with variables, methods, blocks and nested class.
The static keyword belongs to the class rather than instance of the class. Static
variables and methods are also called as class variables and class methods.
When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object
Static Fields
 If you declare a field as static, it is known static field
 The static field can be used to refer the common property of all objects
(that is not unique for each object)
 Suppose there are 100 employees in a company. All employees have its
unique name and id but company name will be same for all 100
employees. Here company name is the common property
 The static field gets memory only once in class area at the time of class
loading.
 Advantage of static field
 Saves memory
 Example
class Emp
{
int id;
String name;
static String companyName="ABC Company";
}
Static method
 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.
 main() method is the most common example of static method. Main()
method is declared as static because it is called before any object of the
class is created
 Limitations of static method
 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in anyway
Example using Static field and static method
class Circle
{
static double PI = 3.1416; //Static field
static int area(int r){ //Static method
return PI*r*r;
}
}
class Test
{
public static void main(String args[]){
System.out.println(" Area of Circle = " +Circle.area(5));
}
}

final keyword
final keyword is used with variable, method and class. It is used for three
purposes namely
 It is used to define Named Constant
If a variable is declared as final, its value cannot be changed (ie) final
variable becomes constant
class Circle
{
final double PI = 3.1415;

}
 It is used to prevent Method Overriding
If a method is declared final, it cannot be overridden. Methods of Math
Class in java.lang package are examples of final methods
class A
{
final void print()
{
System.out.println(" base class");
}
}
class B extends A
{
// error ! final methods cannot be overridden
void print()
{
System.out.println(" sub class ");
}
}
 It is used to prevent Inheritance
If a class is declared final, it cannot be inherited. String class in java.lang
package is an example of final class
final class A
{
// methods and variables of a class
}

// error , A cannot be inherited


class B extends A
{
// methods and variables of a class
}
Nested and Inner Classes
Defining a class within another class is known as nested class. The scope of a
nested class is bounded by the scope of its enclosing class. A nested class has
access to the members, including private members, of the class in which it is
nested. The enclosing class does not have access to the members of the nested
class.
Types of nested classes
 Static nested classes
A static nested class must access the members of its enclosing class
through an object. It cannot refer to members of its enclosing class
directly.
Non-static nested classes
An inner class is a non-static nested class. It has access to all of the
variables and methods of its outer class and may refer to them directly.
Thus, an inner class is fully within the scope of its enclosing class.
Example
class outer //Enclosing class
{
int outer_x =10;

class inner //Inner Class


{
void display()
{
System.out.println("outer_x = "+outer_x);
}
}
void test()
{
inner i = new inner();
i.display();
}
public static void main(String[] args)
{
outer o = new outer();
o.test();
}
}

Command Line Argument


Command line arguments are the arguments that are passed to a program
when it is invoked. To access the command line arguments inside a java
program is quite easy. They are stored as string in the string array parameter
of main() method
Example
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
To run the above program in Command prompt, use as follows
java filename Arg1 Agr2 Agr3
Eg – java cmd 10 20 30
Output
10
20
30
To run the program in Netbeans IDE, follow as given below
 Choose File->Project Properties
 Select Run node from Left categories
 Type Command Line argument in the Argument Textbox
 Run the project (Don‟t use Run file option)

Note
Refer class note for the topic “String”

You might also like