Unit-2
Class fundamentals
 A class is a template that defines the form of an
object.
 It specifies both the data and code that will operate
on that data.
 Objects are instance of class
 Memories and variables that constitute a class are
called members
 Also called as instance variables.
General form of class
class classname{
type var1;
type var2;…
type varN;
type method1(parameters){
}
type method2(parameters){
}
….
}
 A main() method is required only if that class is
starting point for your program
 Java applications, such as applets don’t require a
main() function.
 Defining a class:
 Ex: class vehicle{
int passengers; ///no. of passengers
int fuel; //fuel capcity
int mileage; //fuel consumption per mile
}
 A class definition creates a new data type.
 Here data type is named as vehicle
 To create an object, you will use the statement such as
 Vehicle minivan=new Vehicle();
 Now, minivan is an instance of vehicle
 To access the data members or methods defined in the
class, we should use dot operator
 Object.member
 In order to assign the value for no. of passengers in
mininvan we should use
 minivan.passengers=15;
class vehicle{
int passengers; ///no. of passengers
int fuel; //fuel capcity
int mileage; //fuel consumption per mile
}
class VehicleDemo{
public static void main(String args[]){
Vehicle minivan=new Vehicle();
int range;
minivan.passengers=7;
minivan.fuel=16;
minivan.mileage=7;
range=minivan.fuel*minivan.mileage;
System.out,print(“Minivan can hold “+minivan.passengers+”
with the range”+range);
}
}
 Creating multiple objects of the same class wont affect
the value unless it refers to same object.
 Creating two vehicles named minivan and sportscar of
type vehicle class
class vehicle{
int passengers;
int fuel;
int mileage;
}
class VehicleDemo{
public static void main(String
args[]){
Vehicle minivan=new Vehicle();
Vehicle sportscar=new Vehicle();
int range1,range2;
minivan.passengers=7;
minivan.fuel=16;
minivan.mileage=7;
range1=minivan.fuel*minivan.mile
age;
System.out,print(“Minivan can
hold “+minivan.passengers+”
with the range”+range);
sportscar.passengers=2;
sportscar.fuel=14;
sportscar.mileage=12;
range2=sportscar.fuel*sportscar
.milege;
System.out,print(“Minivan can
hold
“+sportscar.passengers+”
with the range”+range2);
}
}
How objects are created
 Vehicle minivan=new Vehicle();
 It declares a variable called minivan of the class type
Vehicle
 It’s a variable that can refer to an object
 New operator , creates a physical copy of object and
assigns to minivan a reference to that object.
 New operator dynamically allocates memory for an
object and returns a reference to it.
 Vehicle minivan;
 Minivan=new Vehicle();
Reference variables and
assignment
 Assigning one object to another, does not copy the
contents but it refers to the same object.
 Vehicle car1=new Vehicle();l
 Vehicle car2=car1;
 Here the contents of car1 is not copied to car2, instead
both car1 and car2 refer to the same object
 car1.mileage=26;
 System.out.printnln(car1.mileage);
 System.out.println(car2.mileage);
Methods
 Methods are subroutines that manipulate the data
defined by the class
 It contains one or more statements.
 Each method should perform only one tasks.
 Each method has a name and it is used to call in the
main() function
 Java keywords cannot be used as method name
 Method will have parenthesis after its name
ret_type name(parameter_list){
}
 ret_type specifies the type of data returned by the
method
 Method which does not return anything, should return
a type called void.
 parameter_list is a sequence of type and identifier
pairs seperated by commas.
 If the method has no parameters, the parameters list
will be empty.
Adding a method to the vehicle
classclass vehicle{
int passengers;
int fuel;
int mileage;
void range(){
System.out.println(“Range
is”+fuel*mileage);
}
}
class VehicleDemo{
public static void main(String args[]){
Vehicle minivan=new Vehicle();
Vehicle sportscar=new Vehicle();
minivan.passengers=7;
minivan.fuel=16;
minivan.mileage=7;
System.out,print(“Minivan can
hold “+minivan.passengers);
Minivan.range();
sportscar.passengers=2;
sportscar.fuel=14;
sportscar.mileage=12;
System.out,print(“Sportscar can
hold “+sportscar.passengers);
Sportscar.range();
}
}
Returning from a method
 There are two forms of return
 One for use in void methods
 One for returning methods
 In a void method, the immediate termination of the
method can be done by using this form of return
 A void method will terminate when it comes across the
closing curly braces.
void myMet(){
int i;
for(i=0;i<10;i++)
if(i==5) return;
System.out.println();
}
Returning a value
 Most of the methods will return a value.
 return value;
 Here value is the returned
 Non-void method must return a value by using this
form of return.
Return type for the methodclass vehicle{
int passengers;
int fuel;
int mileage;
int range(){
return fuel*mileage;
}
}
class VehicleDemo{
public static void main(String args[]){
Vehicle minivan=new Vehicle();
Vehicle sportscar=new Vehicle();
int range1,range2;
minivan.passengers=7;
minivan.fuel=16;
minivan.mileage=7;
System.out,print(“Minivan can
hold “+minivan.passengers);
range1=Minivan.range();
System.out.println(range1);
sportscar.passengers=2;
sportscar.fuel=14;
sportscar.mileage=12;
System.out,print(“Sportscar can
hold “+sportscar.passengers);
range2=Sportscar.range();
System.out.println(range2);
}
}
Using parameters
 Value passed to a method is called argument
 More than a value can be passed into a method.
 Inside a method, the variable that receives the
argument is called parameters.
 Simple example that uses a parameter
 Inside Chksum class, a method isEven() returns true if
the value passed to it is even otherwise it returns false.
class chkSum{
boolean isEven(int x)
if(x%2==0)
return true;
else
return false;
}
class demo{
public static void main(String args[]){
chkSum e=new chkSum();
if(e.isEven(10))
System.out.println(“10 is even”);
else
System.out.println(“10 is not even”);
}
}
Adding parameterized method to
vehicle class
class Vehicle{
int passengers;
int fuel;
int milage;
int range(){
return milage*fuel;
}
double fuelneeded(int miles){
returns (double) miles/milage;
}
}
class Computefuel{
public static void main(String args[]){
Vehicle minivan=new Vehicle();
Vehicle sportscar=new Vehicle();
int dist=252;
minivan.passengers=7;
minivan.fuel=16;
minivan.milage=23;
sportsacar.passengers=2;
sportscar.fuel=14;
sportscar.milage=12;
double gallons=minivan.fuelneeded(dist);
System.out.println(“Fuel required by
minivan and sportscar is
:”+minivan.fuelneeded(dist)+”t”+
sportscar.fuelneeded(dist));
}
}
Constructors
 Having multiple statements for assigning the data
members in the main class is error prone.
 A constructor initializes an object when it is created
 It has the same name as the class
 Syntax is similar to the method.
 Constructors do not have explicit return type.
 Java provides a default constructor that initializes all
the data members by the default values by it self.
 i.e. zero for numeric type, null for reference type and
false for boolean type.
class Myclass{
int x;
Myclass(){
x=10;
}
}
class CLassDemo{
public static void main(String args[]){
Myclass m1=new Myclass();
Myclass m2=new Myclass();
System.out.println(m1.x+”t”+m2.x);
}
}
Parameterized constructors
 Constructors accept one or more parameters
 Parameters are added in the same way as the methods
 Declare them inside the parenthesis after the
constructors name
 Ex.
class Myclass{
int x;
Myclass(int i){
x=i;
}
}
class ParamCLassDemo{
public static void main(String args[]){
Myclass m1=new Myclass(10);
Myclass m2=new Myclass(88);
System.out.println(m1.x+”t”+m2.x);
}
}
The new operator
 class_var =new class_name(arg_list);
 class_var is a variable of the class type being created.
 The class name is the name of the class that is being
instantiated.
 If a class does not define its own constructor , new will
use the default constructor supplied by java.
 The new operator returns a reference to a newly
created object, which is assigned to class_var.
Garbage collection and finalizers
 Objects are dynamically allocated from a pool of free
memory by using the new operator.
 Memory is not infinite, it can be exhausted.
 many languages like C++ memory reallocation is
handled manually, the programmer uses delete
operator to free the memory that was allocated by the
new operator
 Java uses a approach called garbage collection that
reclaims memory automatically
 When no references to an object exists, then object is
assumed to be no longer needed and memory
occupied by the object is released.
 The recycled memory can be used for further
allocation.
 The garbage collector will usually run when two
conditions are met: there are objects to recycle and
there is need to recycle them
 Java garbage collection requires times hence the Java
run-time will perform garbage collection when it is
appropriate.
The finalize() method
 A method that is called just before an objects final
destruction by the garbage collector.
 Can be used to ensure that an object terminates
cleanly.
 Inside the finalise method, we will specify those
actions that must be performed before an object is
destroyed.
protected void finalize()
{
//finalization code here
}
 The keyword protected is a specifier that prevents
access to finalize() by code defined outside the class.
 Finalize() is called just before garbage collection.
 This means we cannot predict when finalize function
will be called by the java runtime
 If program ends before the garbage collection occurs
then finalize() will not be executed.
 Hence used as backup procedure to ensure the proper
handling of the resources
The this keyword
 When a method is called, it is automatically passed an
implicit argument that is a reference to the invoking object,
this reference is called this reference.
class Pwr{
double b,val;
int e;
Pwr(double b,int e)
{
this.b=b;
this.e=e;
}
}
Controlling access to class
members
 There are two access modifiers: private and public
 A public member can be freely accessed by the code
defined outside the class.
 A private member can be accessed only by the other
methods defined in the class
 Restricting the access to class members is a
fundamental part of object oriented programming
because it helps to prevent the misuse of object.
 When correctly implemented, class creates a black box
that can be used, but the inner workings of which are
not open to tampering.
Java access modifiers
 Achieved through the use of three access modifiers:
 private
 public
 protected
 If no access modifier is specified, the default access setting
is assumed.
 When a member of class is public specifier, that member
can be accessed by any other code in the program
 When a member of class is private specifier , that member
can be accessed only by other members of its class.
 Default access modifier is same as public access modifier.
Chap2 class,objects
Chap2 class,objects

Chap2 class,objects

  • 1.
  • 2.
    Class fundamentals  Aclass is a template that defines the form of an object.  It specifies both the data and code that will operate on that data.  Objects are instance of class  Memories and variables that constitute a class are called members  Also called as instance variables.
  • 3.
    General form ofclass class classname{ type var1; type var2;… type varN; type method1(parameters){ } type method2(parameters){ } …. }
  • 4.
     A main()method is required only if that class is starting point for your program  Java applications, such as applets don’t require a main() function.  Defining a class:  Ex: class vehicle{ int passengers; ///no. of passengers int fuel; //fuel capcity int mileage; //fuel consumption per mile }
  • 5.
     A classdefinition creates a new data type.  Here data type is named as vehicle  To create an object, you will use the statement such as  Vehicle minivan=new Vehicle();  Now, minivan is an instance of vehicle  To access the data members or methods defined in the class, we should use dot operator  Object.member  In order to assign the value for no. of passengers in mininvan we should use  minivan.passengers=15;
  • 6.
    class vehicle{ int passengers;///no. of passengers int fuel; //fuel capcity int mileage; //fuel consumption per mile } class VehicleDemo{ public static void main(String args[]){ Vehicle minivan=new Vehicle(); int range; minivan.passengers=7; minivan.fuel=16; minivan.mileage=7; range=minivan.fuel*minivan.mileage; System.out,print(“Minivan can hold “+minivan.passengers+” with the range”+range); } }
  • 7.
     Creating multipleobjects of the same class wont affect the value unless it refers to same object.  Creating two vehicles named minivan and sportscar of type vehicle class
  • 8.
    class vehicle{ int passengers; intfuel; int mileage; } class VehicleDemo{ public static void main(String args[]){ Vehicle minivan=new Vehicle(); Vehicle sportscar=new Vehicle(); int range1,range2; minivan.passengers=7; minivan.fuel=16; minivan.mileage=7; range1=minivan.fuel*minivan.mile age; System.out,print(“Minivan can hold “+minivan.passengers+” with the range”+range); sportscar.passengers=2; sportscar.fuel=14; sportscar.mileage=12; range2=sportscar.fuel*sportscar .milege; System.out,print(“Minivan can hold “+sportscar.passengers+” with the range”+range2); } }
  • 9.
    How objects arecreated  Vehicle minivan=new Vehicle();  It declares a variable called minivan of the class type Vehicle  It’s a variable that can refer to an object  New operator , creates a physical copy of object and assigns to minivan a reference to that object.  New operator dynamically allocates memory for an object and returns a reference to it.  Vehicle minivan;  Minivan=new Vehicle();
  • 10.
    Reference variables and assignment Assigning one object to another, does not copy the contents but it refers to the same object.  Vehicle car1=new Vehicle();l  Vehicle car2=car1;  Here the contents of car1 is not copied to car2, instead both car1 and car2 refer to the same object  car1.mileage=26;  System.out.printnln(car1.mileage);  System.out.println(car2.mileage);
  • 11.
    Methods  Methods aresubroutines that manipulate the data defined by the class  It contains one or more statements.  Each method should perform only one tasks.  Each method has a name and it is used to call in the main() function  Java keywords cannot be used as method name  Method will have parenthesis after its name ret_type name(parameter_list){ }
  • 12.
     ret_type specifiesthe type of data returned by the method  Method which does not return anything, should return a type called void.  parameter_list is a sequence of type and identifier pairs seperated by commas.  If the method has no parameters, the parameters list will be empty.
  • 13.
    Adding a methodto the vehicle classclass vehicle{ int passengers; int fuel; int mileage; void range(){ System.out.println(“Range is”+fuel*mileage); } } class VehicleDemo{ public static void main(String args[]){ Vehicle minivan=new Vehicle(); Vehicle sportscar=new Vehicle(); minivan.passengers=7; minivan.fuel=16; minivan.mileage=7; System.out,print(“Minivan can hold “+minivan.passengers); Minivan.range(); sportscar.passengers=2; sportscar.fuel=14; sportscar.mileage=12; System.out,print(“Sportscar can hold “+sportscar.passengers); Sportscar.range(); } }
  • 14.
    Returning from amethod  There are two forms of return  One for use in void methods  One for returning methods  In a void method, the immediate termination of the method can be done by using this form of return  A void method will terminate when it comes across the closing curly braces. void myMet(){ int i; for(i=0;i<10;i++) if(i==5) return; System.out.println(); }
  • 15.
    Returning a value Most of the methods will return a value.  return value;  Here value is the returned  Non-void method must return a value by using this form of return.
  • 16.
    Return type forthe methodclass vehicle{ int passengers; int fuel; int mileage; int range(){ return fuel*mileage; } } class VehicleDemo{ public static void main(String args[]){ Vehicle minivan=new Vehicle(); Vehicle sportscar=new Vehicle(); int range1,range2; minivan.passengers=7; minivan.fuel=16; minivan.mileage=7; System.out,print(“Minivan can hold “+minivan.passengers); range1=Minivan.range(); System.out.println(range1); sportscar.passengers=2; sportscar.fuel=14; sportscar.mileage=12; System.out,print(“Sportscar can hold “+sportscar.passengers); range2=Sportscar.range(); System.out.println(range2); } }
  • 17.
    Using parameters  Valuepassed to a method is called argument  More than a value can be passed into a method.  Inside a method, the variable that receives the argument is called parameters.  Simple example that uses a parameter  Inside Chksum class, a method isEven() returns true if the value passed to it is even otherwise it returns false.
  • 18.
    class chkSum{ boolean isEven(intx) if(x%2==0) return true; else return false; } class demo{ public static void main(String args[]){ chkSum e=new chkSum(); if(e.isEven(10)) System.out.println(“10 is even”); else System.out.println(“10 is not even”); } }
  • 19.
    Adding parameterized methodto vehicle class class Vehicle{ int passengers; int fuel; int milage; int range(){ return milage*fuel; } double fuelneeded(int miles){ returns (double) miles/milage; } } class Computefuel{ public static void main(String args[]){ Vehicle minivan=new Vehicle(); Vehicle sportscar=new Vehicle(); int dist=252; minivan.passengers=7; minivan.fuel=16; minivan.milage=23; sportsacar.passengers=2; sportscar.fuel=14; sportscar.milage=12; double gallons=minivan.fuelneeded(dist); System.out.println(“Fuel required by minivan and sportscar is :”+minivan.fuelneeded(dist)+”t”+ sportscar.fuelneeded(dist)); } }
  • 20.
    Constructors  Having multiplestatements for assigning the data members in the main class is error prone.  A constructor initializes an object when it is created  It has the same name as the class  Syntax is similar to the method.  Constructors do not have explicit return type.  Java provides a default constructor that initializes all the data members by the default values by it self.  i.e. zero for numeric type, null for reference type and false for boolean type.
  • 21.
    class Myclass{ int x; Myclass(){ x=10; } } classCLassDemo{ public static void main(String args[]){ Myclass m1=new Myclass(); Myclass m2=new Myclass(); System.out.println(m1.x+”t”+m2.x); } }
  • 22.
    Parameterized constructors  Constructorsaccept one or more parameters  Parameters are added in the same way as the methods  Declare them inside the parenthesis after the constructors name  Ex.
  • 23.
    class Myclass{ int x; Myclass(inti){ x=i; } } class ParamCLassDemo{ public static void main(String args[]){ Myclass m1=new Myclass(10); Myclass m2=new Myclass(88); System.out.println(m1.x+”t”+m2.x); } }
  • 24.
    The new operator class_var =new class_name(arg_list);  class_var is a variable of the class type being created.  The class name is the name of the class that is being instantiated.  If a class does not define its own constructor , new will use the default constructor supplied by java.  The new operator returns a reference to a newly created object, which is assigned to class_var.
  • 25.
    Garbage collection andfinalizers  Objects are dynamically allocated from a pool of free memory by using the new operator.  Memory is not infinite, it can be exhausted.  many languages like C++ memory reallocation is handled manually, the programmer uses delete operator to free the memory that was allocated by the new operator  Java uses a approach called garbage collection that reclaims memory automatically  When no references to an object exists, then object is assumed to be no longer needed and memory occupied by the object is released.
  • 26.
     The recycledmemory can be used for further allocation.  The garbage collector will usually run when two conditions are met: there are objects to recycle and there is need to recycle them  Java garbage collection requires times hence the Java run-time will perform garbage collection when it is appropriate.
  • 27.
    The finalize() method A method that is called just before an objects final destruction by the garbage collector.  Can be used to ensure that an object terminates cleanly.  Inside the finalise method, we will specify those actions that must be performed before an object is destroyed. protected void finalize() { //finalization code here }
  • 28.
     The keywordprotected is a specifier that prevents access to finalize() by code defined outside the class.  Finalize() is called just before garbage collection.  This means we cannot predict when finalize function will be called by the java runtime  If program ends before the garbage collection occurs then finalize() will not be executed.  Hence used as backup procedure to ensure the proper handling of the resources
  • 29.
    The this keyword When a method is called, it is automatically passed an implicit argument that is a reference to the invoking object, this reference is called this reference. class Pwr{ double b,val; int e; Pwr(double b,int e) { this.b=b; this.e=e; } }
  • 30.
    Controlling access toclass members  There are two access modifiers: private and public  A public member can be freely accessed by the code defined outside the class.  A private member can be accessed only by the other methods defined in the class  Restricting the access to class members is a fundamental part of object oriented programming because it helps to prevent the misuse of object.  When correctly implemented, class creates a black box that can be used, but the inner workings of which are not open to tampering.
  • 31.
    Java access modifiers Achieved through the use of three access modifiers:  private  public  protected  If no access modifier is specified, the default access setting is assumed.  When a member of class is public specifier, that member can be accessed by any other code in the program  When a member of class is private specifier , that member can be accessed only by other members of its class.  Default access modifier is same as public access modifier.