[go: up one dir, main page]

0% found this document useful (0 votes)
82 views29 pages

Zoom 1

The document discusses the fundamentals of classes, objects, and methods in Java. It defines a class as a template that specifies the form of an object, including data and code. An object is an instance of a class. The general form of a class includes instance variables and methods. Methods can return values or be void. Parameters can be passed to methods to customize their behavior.

Uploaded by

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

Zoom 1

The document discusses the fundamentals of classes, objects, and methods in Java. It defines a class as a template that specifies the form of an object, including data and code. An object is an instance of a class. The general form of a class includes instance variables and methods. Methods can return values or be void. Parameters can be passed to methods to customize their behavior.

Uploaded by

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

Classes, Objects, And

Methods

By: Nagesh B S
1

1 Asst. Professor
Dept. of MCA
RNSIT, Bengaluru

Java Programming
Class Fundamentals
 A class is a template that defines the form of an object.
 It specifies both the data and the code that will operate
on that data.
 Java uses a class specification to construct objects.
 Objects are instances of a class. Thus, a class is
essentially a set of plans that specify how to build an
object.
 methods and variables that constitute a class are called
members of the class.
 The data members are also referred to as instance
variables.
 very simple classes might contain only methods or only
instance variables, most real-world classes contain both.
The General Form of a Class
class classname {
// declare instance variables
type var1;
type var2;
// ...
type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}
 A well-designed class should define one and only one logical entity.
 For example, a class that stores names and telephone numbers will not
normally also store information about the stock market, average rainfall,
sunspot cycles, or other unrelated information.
 Example

class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}
 A class definition creates a new data type. In this case, the new data type is
called Vehicle.
To create a Vehicle object

Vehicle minivan = new Vehicle(); // create a Vehicle object called minivan


 After this statement executes, minivan will be an instance of Vehicle.
 Each time you create an instance of a class, you are creating an object that contains its
own copy of each instance variable defined by the class.
 Thus, every Vehicle object will contain its own copies of the instance variables
passengers, fuelcap, and mpg.

To access these variables you will use the dot (.) operator.
object.member
minivan.fuelcap = 16;
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}
class VehicleDemo {
public static void main(String args[]) {
vehicle minivan = new vehicle();
int range;
// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
// compute the range assuming a full tank of gas
range = minivan.fuelcap * minivan.mpg;
System.out.println("minivan can carry " + minivan.passengers + " with a range of " +
range);
} }
 Assume the filename as VehicleDemo.java .
 It is not necessary for both the Vehicle and the VehicleDemo class to be in
the same source file.
 The java compiler put each class in its own file, called Vehicle.java and
VehicleDemo.java, respectively.
 To run this program, you must execute VehicleDemo.class.
// This program creates two Vehicle objects.
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
// This class declares an object of type Vehicle.
class TwoVehicles {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
// assign values to fields in sportscar
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
// compute the ranges assuming a full tank of gas
range1 = minivan.fuelcap * minivan.mpg;
range2 = sportscar.fuelcap * sportscar.mpg;
System.out.println("Minivan can carry " + minivan.passengers + " with a range of
" + range1);
System.out.println("Sportscar can carry " + sportscar.passengers + " with a range
of " + range2);
}
}
How Objects Are Created
Vehicle minivan = new Vehicle();
 First, it declares a variable called minivan of the class type Vehicle.
 This variable does not define an object. Instead, it is simply a variable that can refer to
an object.
 Second, the declaration creates a physical copy of the object and assigns to minivan
a reference to that object.
 This is done by using the new operator.
 The new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it.
 In Java, all class objects must be dynamically allocated.
 preceding statement can be rewritten like this to show each step individually:

Vehicle minivan; // declare reference to object


minivan = new Vehicle(); // allocate a Vehicle object
Methods

 Methods are subroutines that manipulate the data defined by the class and, in
many cases, provide access to that data.
 Can give a method whatever name you please, but…..
 Remember that main( ) is reserved for the method that begins execution of
your program. Also ,don’t use Java’s keywords for method names.

ret-type name( parameter-list ) {


// body of method
}
 For example, the following version of Vehicle contains a method called
range( ) that displays the range of the vehicle.
class Vehicle {
// assign values to fields in sportscar
int passengers; // number of passengers
sportscar.passengers = 2;
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon sportscar.fuelcap = 14;
// Display the range. sportscar.mpg = 12;
void range() { System.out.print("Minivan can carry " +
System.out.println("Range is " + fuelcap * mpg);
minivan.passengers + ". ");
} minivan.range(); // display range of
}
minivan
class AddMeth {
public static void main(String args[]) {
System.out.print("Sportscar can carry " +
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle(); sportscar.passengers +". ");

int range1, range2; sportscar.range(); // display range of


// assign values to fields in minivan sportscar.
minivan.passengers = 7; }
minivan.fuelcap = 16; }
minivan.mpg = 21;
Returning from a Method
 A void method can return in one of two ways
 its closing curly brace is reached
 return statement is executed.

void myMeth() {
int i;
for(i=0; i<10; i++) {
if(i == 5) return; // stop at 5
System.out.println();
}
}
Returning a Value
 Methods return a value to the calling routine using this form of return:

return value;
 This form of return can be used only with methods that have a non-
void return type.
 A non-void method must return a value by using this form of return.
class Vehicle {
// assign values to fields in sportscar
int passengers; // number of passengers
sportscar.passengers = 2;
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon sportscar.fuelcap = 14;
// Display the range. sportscar.mpg = 12;
void range() { range1=minivan.range();
return mpg * fuelcap; System.out.print("Minivan can carry " +
} minivan.passengers + “with range of “ +
}
range1+ “Miles”);
class AddMeth {
range2=sportscar.range();
public static void main(String args[]) {
System.out.print(“sportscar can carry " +
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle(); sportscar.passengers + “with range of “ +

int range1, range2; range1+ “Miles”);


// assign values to fields in minivan }
minivan.passengers = 7; }
minivan.fuelcap = 16;
minivan.mpg = 21;
Using Parameters
 It is possible to pass one or more values to a method when the
method is called.
 A value passed to a method is called an argument.
 Inside the method, the variable that receives the argument is
called a parameter.
 Parameters are declared inside the parentheses that follow the
method’s name.
 A method can have more than one parameter. Declare each
parameter, separating one from the next with a comma.
// A simple example that uses a parameter.
class ChkNum {
// return true if x is even
boolean isEven(int x) {
if((x%2) == 0) return true;
else return false;
}
}
class ParmDemo {
public static void main(String args[]) {
ChkNum e = new ChkNum();
if(e.isEven(10)) System.out.println("10 is even.");
if(e.isEven(9)) System.out.println("9 is even.");
if(e.isEven(8)) System.out.println("8 is even.");
}
}
class Factor {
boolean isFactor(int a, int b) {
if( (b % a) == 0) return true;
else return false;
}
}
class IsFact {
public static void main(String args[]) {
Factor x = new Factor();
if(x.isFactor(2, 20)) System.out.println("2 is factor");
if(x.isFactor(3, 20)) System.out.println("this won't be displayed");
}
}
class Vehicle { // assign values to fields in minivan
int passengers; // number of passengers minivan.passengers = 7;
int fuelcap; // fuel capacity in gallons minivan.fuelcap = 16;
int mpg; // fuel consumption in miles per minivan.mpg = 21;
gallon // assign values to fields in
// Return the range. sportscar
int range() { sportscar.passengers = 2;
return mpg * fuelcap; sportscar.fuelcap = 14;
} sportscar.mpg = 12;
// Compute fuel needed for a given gallons = minivan.fuelneeded(dist);
distance. System.out.println("To go " + dist + "
double fuelneeded(int miles) { miles minivan needs " + gallons + "
return (double) miles / mpg; gallons of fuel.");
} gallons = sportscar.fuelneeded(dist);
} System.out.println("To go " + dist + "
miles sportscar needs " + gallons + "
class CompFuel { gallons of fuel.");
public static void main(String args[]) { }
Vehicle minivan = new Vehicle(); }
Vehicle sportscar = new Vehicle();
double gallons;
int dist = 252;
Constructors
 The instance variables of each Vehicle object had to be set manually using
a sequence of statements.
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
 Programmers might forget to set one of the fields, there is simply a better
way to accomplish this task. I.e. constructors
 A constructor initializes an object when it is created.
 It has the same name as its class and is syntactically similar to
a method.
 Constructors have no explicit return type.
 We use constructor to give initial values to the instance
variables defined by the class, or to perform any other start-up
procedures required to create a fully formed object.
 All classes have constructors, whether you define one or not,
 Java automatically provides a default constructor that initializes all member variables to zero.
 Once we define our own constructor, the default constructor is no longer used.
// A simple constructor.
class MyClass {
int x;
// This is the constructor for MyClass
//MyClass() {
//x = 10;
//}
}
class ConsDemo {
public static void main(String args[]) {

MyClass t1 = new MyClass();


MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}}
Parameterized Constructors
 Parameters are added to a constructor in the same way that they are added to a method
 Declare them inside the parentheses after the constructor’s name.
// A parameterized constructor.
class MyClass {
int x;
MyClass(int i) {
x = i;
}
}
class ParmConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
System.out.println(t1.x + " " + t2.x);
}}
Garbage Collection and Finalizers
 Objects are dynamically allocated from a pool of free memory by using the new
operator.
 Memory is not infinite, and the free memory can be exhausted.
 it is possible for new to fail because there is insufficient free memory to
create the desired object.
 The recovery of free memory from unused objects and making that memory
available for subsequent reallocation.
 Java’s garbage collection system reclaims objects automatically behind the scenes,
without any programmer intervention.
 when no references to an object exist, that object is assumed to be no longer
needed, and the memory occupied by the object is released.
 The garbage collector will usually run only when two conditions are met: there are
objects to recycle, and there is a need to recycle them.
 Remember, garbage collection takes time, so the Java run-time system does it only
when necessary.
 Thus, you can’t know precisely when garbage collection will take place.
The finalize( ) Method

You might also like