defining a classtmyn1 defining a class a class is a template that defines the form of an object. it...

53
Defining a Class tMyn 1 Defining a Class 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.

Upload: shannon-greene

Post on 13-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Defining a Class tMyn 1

Defining a Class

• 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.

Defining a Class tMyn 2

• When you define a class, you declare its exact form and nature. You do this by specifying the instance variables that it contains and the methods that operate on them.

• Although very simple classes might contain only methods or only instance variables, most real-world classes contain both.

• A class is created by using the keyword class:

Defining a Class tMyn 3

class classname{

//declare instance variablestype var1;type var2;//…//declare methodstype method1(parameters){

//body of method}type method2(parameters){

//body of method}//…

}

Defining a Class tMyn 4

• 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.

• The point here is that well-designed class groups logically connected information.

• Our first class does not have any instance variables but only one method, displayMessage():

Defining a Class tMyn 5

package TimoSoft;

public class GradeBook{ public void displayMessage() { System.out.println("Welcome to the GradeBook!"); }}

Defining a Class tMyn 6

• Methods are subroutines that usually manipulate the data defined by the class and, in many cases, provide access to that data.

• In most cases, other parts of your program will interact with a class through its methods.

• Usually each method performs only one task.• The general form of a method is:

return-type name(parameter-list)

{

//body of method

}

Defining a Class tMyn 7

• The type of data returned by the method 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 parameter list is a sequence of type and identifier pairs separated by commas.

• Parameters are essentially variables that receive the value of the arguments passed to the method when it is called.

• To add a method to a class you just specify it within class’s declaration.

Defining a Class tMyn 8

• Next we have to write the main() method to test our first class:

Defining a Class tMyn 9

package TimoSoft;

public class GradeBookTest { public static void main(String[] args) { GradeBook myGradeBook=new GradeBook(); myGradeBook.displayMessage(); }}

run:Welcome to the GradeBook!BUILD SUCCESSFUL (total time: 2 seconds)

Defining a Class tMyn 10

• In the preceding program, the following line was used to declare an object of type GradeBook:

GradeBook myGradeBook=new GradeBook();

• This declaration performs two functions. First, it declares a variable called myGradeBook of the class type GradeBook. This variable does not define an object. Instead, it is simply a reference variable that can refer to an object of type GradeBook.

Defining a Class tMyn 11

• Second, the declaration creates a physical copy of the object and assigns to myGradeBook 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.

• This reference is, more or less, the address in memory of the object allocated by new.

• This reference is then stored in a variable myGradeBook. Thus, in Java, all class objects must be dynamically allocated.

Defining a Class tMyn 12

• The class name followed by parentheses specifies the constructor for the class.

• If a class does not define its own constructor (like in the previous example), new will use the default constructor supplied by Java.

• Since memory is finite, it is theoretically possible that new will not be able to allocate memory for an object because insufficient memory exists.

• If this happens, a run-time exception will occur.

Defining a Class tMyn 13

• The two steps combined in the preceding statement can be rewritten like this to show each step individually:

GradeBook myGradeBook;

myGradeBook=new GradeBook ();

• The first line declares myGradeBook as a reference variable to an object of type GradeBook. Thus, myGradeBook is a variable that can refer to an object, but it is not an object, itself. At this point, myGradeBook contains the value null, which means that it does not refer to an object.

Defining a Class tMyn 14

• The next line creates a new GradeBook object and assigns a reference to it to myGradeBook. Now, myGradeBook is linked with an object.

• For example, consider the following fragment:

Vehicle car1=new Vehicle();

Vehicle car2=car1;

• Interpretation: reference variables car1 and car2 will both refer to the same physical object. To explain it some other way: reference variables car1 and car2 does both have the same address content.

Defining a Class tMyn 15

• In the preceding example we used the dot operator.• The dot operator links the name of an object with the

name of a member.

Defining a Class tMyn 16

• Now that the very fundamentals of classes has been covered, we can take an example where we read integers from the keyboard using the class Scanner:

Defining a Class tMyn 17

package addthem;

import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int number1, number2, sum; System.out.print("Enter first integer: "); number1=input.nextInt(); System.out.print("Enter second integer: "); number2=input.nextInt(); sum=number1+number2; System.out.printf("Sum is %d\n", sum); }}

Defining a Class tMyn 18

run:Enter first integer: 5Enter second integer: 9Sum is 14BUILD SUCCESSFUL (total time: 20 seconds)

Defining a Class tMyn 19

• At the beginning from the previous example:

Scanner input=new Scanner(System.in);

• This expression creates a Scanner object that reads data typed by the user at the keyboard.

• At the very beginning there was the line

import java.util.Scanner;

• That means that the program uses class Scanner.

Defining a Class tMyn 20

• Why do we need to import class Scanner, but not for example class System?

• Most classes you will use in Java programs must be imported.

• For example classes System, Number and Math are in package java.lang, which is implicitly imported into every Java program.

• Thus, all programs can use package java.lang’s classes without explicitly importing them.

Defining a Class tMyn 21

• Actually, the import declaration is not required if we always refer to class Scanner as java.util.Scanner, which includes the full package name and class name. This is known as the class’s fully qualified class name.

Defining a Class tMyn 22

• The last statement was:

System.out.printf("Sum is %d\n", sum);

• The f in the name printf stands for formatted. The format specifier %d is a placeholder for an int value (in this case the value of sum) – the letter d stands for decimal integer.

Defining a Class tMyn 23

• A constructor initializes an object when it is created.• It has the same name as its class and is syntactically

similar to a method.• However, constructors have no explicit return type.• Typically, you will use a constructor to give initial

values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object.

• All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero:

Defining a Class tMyn 24

package TimoSoft;

public class Rectangle{ double width, height; void getWidth() { System.out.println("The width is "+width); } void getHeight() { System.out.println("The height is "+height); }}

Defining a Class tMyn 25

package TimoSoft;

public class RectangleTest {

public static void main(String[] args) { Rectangle first=new Rectangle(); first.getWidth(); first.getHeight(); }}

run:The width is 0.0The height is 0.0BUILD SUCCESSFUL (total time: 0 seconds)

Defining a Class tMyn 26

• However, once you define your own constructor, the default constructor is no longer used.

• Now we add the constructor which initializes the instance variables:

Defining a Class tMyn 27

package TimoSoft;

public class Rectangle{ double width, height; void getWidth() { System.out.println("The width is "+width); } void getHeight() { System.out.println("The height is "+height); }

Defining a Class tMyn 28

void setWidth(double w) { width=w; } void setHeight(double h) { height=h; } Rectangle(double wVal, double hVal) { setWidth(wVal); setHeight(hVal); }}

Defining a Class tMyn 29

package TimoSoft;

public class RectangleTest { public static void main(String[] args) { Rectangle first=new Rectangle(12.5, 7.9); first.getWidth(); first.getHeight(); }}

run:The width is 12.5The height is 7.9BUILD SUCCESSFUL (total time: 0 seconds)

Defining a Class tMyn 30

• Each object of the class will have its own copy of each of the non-static fields or instance variables that appear in the class definition.

• Each object will have its own values for each instance variable.

• The name instance variable originates from the fact that an object is an instance or an occurrence of a class, and the values stored in the instance variables for the object differentiate the object from others of the same class type.

Defining a Class tMyn 31

• Although methods are specific to objects of a class, there is only ever one copy of each method in memory that is shared by all objects of the class, as it would be extremely expensive to replicate all instance methods for each object.

• A special mechanism ensures that each time you call a method the code executes in a manner that is specific to an object.

• Each time an instance method is called, the this variable is set to reference the particular class object to which it is being applied.

• The code in the method will then relate to the specific members of the object referred to by this.

Defining a Class tMyn 32

• Parameters are added to a constructor in the same way that they are added to a method: just declare them inside the parentheses after the constructor’s name.

• 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 a method, the variable that receives the argument is called a parameter.

• Parameters are declared inside the parentheses that follow the method’s name.

Defining a Class tMyn 33

• The parameter declaration syntax is the same as that used for variables.

• A parameter is within the scope of its method, and aside from its special task of receiving an argument, it acts like any other local variable.

Defining a Class tMyn 34

• Classes often provide methods to allow clients of the class to set (i.e., assign values to) or get (i.e., obtain the values of) instance variables.

• So often there are “setters” which are called by the constructor.

• The names of these methods need not begin with set or get, but this naming convention is highly recommended.

Defining a Class tMyn 35

• The mutator method, sometimes called a "setter", is most often used in keeping with the principle of encapsulation. According to this principle, instance variables of a class are made private to hide and protect them from other code, and can only be modified by a public member function (the mutator method), which takes the desired new value as a parameter, optionally validates it, and modifies the private instance variable.

Defining a Class tMyn 36

• Often a "setter" is accompanied by a "getter“, also known as an accessor method, which returns the value of the private instance variable.

Defining a Class tMyn 37

• Next modification: The instance variables width and height will be asked from the user:

Defining a Class tMyn 38

package TimoSoft;import java.util.Scanner;

public class Rectangle{ double width, height; void getWidth() { System.out.println("The width is "+width); } void getHeight() { System.out.println("The height is "+height); }

Defining a Class tMyn 39

void setWidth() { Scanner input1= new Scanner(System.in); System.out.print("Enter the width: "); width=input1.nextDouble(); } void setHeight() { Scanner input2= new Scanner(System.in); System.out.print("Enter the height: "); height=input2.nextDouble(); } Rectangle() { setWidth(); setHeight(); }}

Defining a Class tMyn 40

package TimoSoft;

public class RectangleTest {

public static void main(String[] args) { Rectangle first=new Rectangle(); first.getWidth(); first.getHeight(); }}

Defining a Class tMyn 41

run:Enter the width: 34,8Enter the height: 23,4The width is 34.8The height is 23.4BUILD SUCCESSFUL (total time: 26 seconds)

When entering the double value from the keyboard,the delimiter is comma!!

Defining a Class tMyn 42

• If you don’t like the delimiter to be comma with the double type instance variable, you can change the localization:

public static synchronized void setDefault(Locale newLocale)

• Sets the default locale for this instance of the Java

Virtual Machine. So it would be enough to add this in one of the methods:

Defining a Class tMyn 43

package TimoSoft;import java.util.Scanner;import java.util.Locale;public class Rectangle{ double width, height; void getWidth() { System.out.println("The width is "+width); } void getHeight() { System.out.println("The height is "+height); }

Defining a Class tMyn 44

void setWidth() { Locale.setDefault(Locale.ENGLISH); Scanner fromKeyboard= new Scanner(System.in); System.out.print("Enter the width: "); width=fromKeyboard.nextDouble(); } void setHeight() { Locale.setDefault(Locale.ENGLISH); Scanner fromKeyboard= new Scanner(System.in); System.out.print("Enter the height: "); height=fromKeyboard.nextDouble(); } Rectangle() { setWidth(); setHeight(); }}

Defining a Class tMyn 45

package TimoSoft;

public class RectangleTest{ public static void main(String[] args) { Rectangle first=new Rectangle(); first.getWidth(); first.getHeight(); }}

run:Enter the width: 3.5Enter the height: 78.2The width is 3.5The height is 78.2BUILD SUCCESSFUL (total time: 18 seconds)

Defining a Class tMyn 46

• In Java objects are always allocated dynamically from a pool of free memory by using the new operator.

• Memory is not infinite, and the free memory can be exhausted.

• A key component of any dynamic allocation scheme is the recovery of free memory from unused objects, making that memory available for subsequent reallocation.

• In some programming languages, the release of previously allocated memory is handled manually.

Defining a Class tMyn 47

• For example, in C++, you use the delete operator to free memory that was allocated.

• However, Java uses a different, more trouble-free approach: garbage collection.

• Java’s garbage collection system reclaims objects automatically – occurring transparently, behind the scenes, without any programmer intervention.

• It works like this: 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.

• This recycled memory can then be used for a subsequent allocation.

Defining a Class tMyn 48

• Garbage collection occurs only sporadically during the execution of your program.

• It will not occur simply because one or more objects exist that are no longer used.

• For efficiency, 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.

• Thus, you can’t know precisely when garbage collection will take place.

Defining a Class tMyn 49

• Within an instance method or a constructor, this is a reference to the current object – the object whose method or constructor is being called.

• You can refer to any member of the current object from within an instance method or a constructor by using this.

• The most common reason for using this keyword is because a field is shadowed by a method or constructor parameter:

Defining a Class tMyn 50

package TimoSoft;

public class Point{ int x, y; void setXvalue(int x) { this.x=x; } void setYvalue(int y) { this.y=y; } int getXvalue() { return x; }

Defining a Class tMyn 51

int getYvalue() { return y; } Point(int x, int y) { setXvalue(x); setYvalue(y); }}

Defining a Class tMyn 52

package TimoSoft;

public class PointTest{ public static void main(String[] args) { Point first=new Point(3, 4); System.out.println("The coordinate values are "+ first.getXvalue()+" and "+first.getYvalue()+"."); }}

run:The coordinate values are 3 and 4.BUILD SUCCESSFUL (total time: 0 seconds)

Defining a Class tMyn 53

• In the preceding example each argument to the constructor (or actually to the methods setXvalue() and setYvalue()) shadows one of the object’s instance variables.

• Inside the method setXvalue(int x) x is a local copy of the method’s argument. To refer to the Point instance variable x, the method must use this.x.