Vous êtes sur la page 1sur 38

Classes and Objects in Java

Basics of Classes in Java


English to Java dictionary
 Piece of data: value
 Kind of data: type
 Place to store a value: variable
 Structured group of variables: object
 Kind of object: class
 Object of a particular class: class instance
 Variable belonging to an object: instance variable
Values and types
 All data values in Java have a type
 The type of a value determines:
 How the value is stored in memory
 What operations make sense for the value
 How the value can be cast (converted) to
related values
 Types are very helpful in catching
programming errors
Classes
 A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
 The basic syntax for a class definition:

class ClassName [extends


SuperClassName]
{
[fields declaration]
[methods declaration]
}

 Bare bone class – no fields, no methods

public class Circle {


// my circle class
}`
Adding Fields: Class Circle with fields
 Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle

 The fields (data) are also called the instance


varaibles.
Adding Methods
 A class with only data fields has no life. Objects
created by such a class cannot respond to any
messages.
 Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
 The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}
Adding Methods to Class Circle
public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
}
public double area() {
Method Body
return 3.14 * r * r;
}
}
Data Abstraction
 Declare the Circle class, have created a
new data type – Data Abstraction

 Can define variables (objects) of that type:

Circle aCircle;
Circle bCircle;
Class of Circle cont.
 aCircle, bCircle simply refers to a Circle
object, not an object itself.
aCircle bCircle

null null

Points to nothing (Null Reference) Points to nothing (Null Reference)


Creating objects of a class
 Objects are created dynamically using the
new keyword.
 aCircle and bCircle refer to Circle objects
aCircle = new Circle() ; bCircle = new Circle() ;
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;
Creating objects of a class
aCircle = new Circle();
bCircle= new Circle() ;

bCircle = aCircle;

Before Assignment Before Assignment

aCircle bCircle aCircle bCircle

P Q P Q
Automatic garbage collection
Q
 The object does not have a reference and
cannot be used in future.

 The object becomes a candidate for automatic


garbage collection.

 Java automatically collects garbage periodically


and releases the memory used to be used in the
future.
Accessing Object/Circle Data
 Similar to C syntax for accessing data
defined in a structure.

ObjectName.VariableName
ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle();

aCircle.x = 2.0 // initialize center and radius


aCircle.y = 2.0
aCircle.r = 1.0
Executing Methods in Object/Circle
 Using Object Methods:
sent ‘message’ to aCircle

Circle aCircle = new Circle();

double area;
aCircle.r = 1.0;
area = aCircle.area();
Using Circle Class
// Circle.java: Contains Circle class

class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
Constructors
Defining Constructors
 A constructor is a special kind of method that is
designed to perform initializations, such as giving
values to instance variables.
 A constructor is a method that is called when a
new object is created.
 A constructor can perform any action you want,
but it is meant to perform initializations.
 Constructors serve very much the same purpose as
set methods.
Defining Constructors (cont’d)
 Unlike set methods, constructors are called
automatically whenever you create an object
using the new operator.
 Constructors have the same name as the class.
 Constructors are normally overloaded so there
are multiple definitions of the constructor, each
with different numbers or types of parameters.
Differences between Constructor and
Set Methods
 Headings of constructor methods do not have
the word void. They do not return anything,
but unlike other methods that don’t return
values, the word void is omitted.
 Unlike set methods, the constructors give values
to all the instance variables even though there
may not be an argument for each instance
variable.
Differences between Constructor and
Set Methods (cont’d)
 Whenever you define at least one
constructor, you should be sure to
include a constructor with zero
parameters. Such a constructor is called
a default constructor.
Using Constructors
 Constructors are called at the time that you use
new to create an object.
 Whenever a class definition does not have a
constructor definition, Java automatically creates a
default constructor, that is, one with zero
parameters.
 However, once you add at least one constructor,
then you are in charge of all constructors, i.e., no
default constructor is created by Java.
Using Constructors (cont’d)
 When you create a new object with the operator
new, you must always include a call to a
constructor after the operator new.

Circle aCircle=new Circle(5.2,2.5,3);

 If we don’t specify any arguments, the default


constructor is invoked.
Circle newCircle=new Circle();
Using Constructors (cont’d)
 A constructor can be called only when you
create a new object with the operator new.
 newCircle.Circle(5.2,2.5,3); is invalid.
 Since you cannot call a constructor for an
object after it is created, you need some other
way to change the values of the instance
variables of an object.
 That is the purpose of the set methods, e.g.,
newCircle.setCircle(5.2,2.5,3);
More about Constructors
 Constructors are not usually included in
class diagrams.
 Constructors can invoked other methods in
the class, like set methods.
 For most classes you create, you should
also define a default constructor.
An Example Using Constructors
/**
Class for basic pet records: name, age, and weight.
*/
class PersonRecord
{
private String name;
private int age;//in years
private double weight;//in pounds

public PersonRecord( )
{
name = "No name yet.";
age = 0;
weight = 0;
}
Public PersonRecord(String initialName, int initialAge,double initialWeight)
{
name = initialName;
if ((initialAge < 0) || (initialWeight < 0))
{
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else
{
age = initialAge;
weight = initialWeight;
}
}
public PersonRecord(int initialAge)
{
name = "No name yet.";
weight = 0;
if (initialAge < 0)
{
System.out.println("Error: Negative age.");
System.exit(0);
}
else
age = initialAge;
}
Public PersonRecord(double initialWeight)
{
name = "No name yet";
age = 0;
if (initialWeight < 0)
{
System.out.println("Error: Negative weight.");
System.exit(0);
}
else
weight = initialWeight;
}
public void set(String newName, int newAge, double newWeight)
{
name = newName;
if ((newAge < 0) || (newWeight < 0))
{
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else
{
age = newAge;
weight = newWeight;
}
}
public void set(int newAge)
{
if (newAge < 0)
{
System.out.println("Error: Negative age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
public void set(double newWeight)
{
if (newWeight < 0)
{
System.out.println("Error: Negative weight.");
System.exit(0);
}
else
weight = newWeight; //name and age are unchanged.
}
public String getName( )
{
return name;
}
public int getAge( )
{
return age;
}
public double getWeight( )
{
return weight;
}

public void writeOutput( )


{
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}

}
import java.io.*;
class PersonRecordDemo
{
public static void main(String[] args)
{

PersonRecord user1 = new PersonRecord("Jane Doe");


user1.writeOutput( );
user1.set(“joy”,70.5,25);
user1.set(“john”);
user1.writeOutput( );
PersonRecord user2 = new PersonRecord(“neena“,50,23);
user2.writeOutput( );
}
}
BufferedReader & InputStreamReader
Class InputManager{
static String getString() throws IOException{
Bufferedreader br=new BufferedReader(
new InputStreamReader(System.in))
return br.readLine();
}
static int getInt() throws IOException{
return(Integer.parseInt(getString()));
}
static double getDouble() throws IOException{
return(Double.parseDouble(getString()));
}
static double getFloat() throws IOException{
return(Float.parseFloat(getString()));
}
static double getChar() throws IOException{
return(getString().charAt(0));
}
}
class Test{
public static void main(String arg[])throws IOExceptiion{
String name=InputManager.getString();
}
}
Access Modifiers in java
Private Public Protected Default
Same Class Yes Yes Yes Yes
Subclass of same No Yes Yes Yes
package
Non Subclass of No Yes Yes Yes
same package
Subclass of No Yes Yes No
Different package
Non Subclass of No Yes No No
Different package

Vous aimerez peut-être aussi