COMP 110 chapter9

Ace your homework & exams now with Quizwiz!

immutable objects and classes

Objects whose contents cannot be changes=d and their classes. In rder for an object to be immutable, it must meet the following requirements: * All data fields must be private * There can't be any mutator methods for data fields. * No accessor methods can return a reference to a data field that is mutable.

using packages

Packages can be used to organize classes. To do so, you need to add the following line as the first noncomment and nonstatement in the program: package packageName; If a class is defined without the package statement, it is said to be placed in the default package. Java recommends that you place classes into packages rather than using a default package.

private constructor

Used to prohibit the user from creating an instance of a class. For example, there is no reason to create an instance from the math class because all of its data fields and methods are static. To prevent the user from creating objects from the math class, the constructor in java.lang.Math is defined as follows: private Math(){ }

default constructor

A class may be defined without constructors. IN this case, a public no- arg constructor with an empty body is simply defined in the clas. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class.

static method

A method that can be called withoout creatigna a instance of the class.

static vs. instance

A static method, also known as a variable method, is shared by all objects of the class. Static variables store values for the common variables in a common memory location. If one object changes, the value of all objects of the same class are affected. An instance variable is tied to a specific instance of the clas: it is not shared among objects of the same class.

java.util.Date class

A system java uses independent of encapsualtion of date and time. java.util.Date +Date: constructs a date object for the current time. +Date(elapseTime: long): Constructs a data objecct for a given time in miliseconds elapsed January 1, 1970. +toString() String: returns a string representing the date and time. +getTime(); long: Returns the number of miliseconds since January 1, 1970. +settiem(): long: Sets a new elapse time in the object..

class

A template, blueprint, or contract that defines what an object's data fields and methods will be. An object is an instance of a class.

dot(.) operator

After an object is created, its data can be accessed and its methods can be invoked using the dot operator(.), also known as the object member access operator. * ObjectRefVar data field references a data field in the object. * ObjectRefVar. method(arguements) invokes a method on the object.

this keyword

Referes to the object itself. It can be used inside a constructor to invoke another constructor of the same class or to reference the object's members. a. public class Circle{ private double radius; ... public double getArea(){ return this.radius*this.radius+Math.Pi } public string toString(){ return "radius"+ this.radius+area+this.getArea(); } } Is equivalent to: b. public class Circle{ private double radius;... public double getArea(); return radius*radius*Math.PI; } public String toString(); return "radius"+"radius+"area"+getArea(); (a) uses this to reference the object's radius and invokes it's getArea method explicitly. The this reference is omitted for brevity in (b).

main class

The class that contians the main method, whereas the circle class does not.

default field values

The default c=vlaue of a data field is 0 for a numeric type, false for a boolean type,and \u000 for a char type. However, Java assigns no default value to a local variable inside a method.

Unified Modeling Language (UML)

The notation is called a UML class diagram, or simply, a class diagram. In the class diagram, the data field is denoted as: dataFieldName: dataFieldType The constructor is denoted as: className(parameterName: characterType) The method is denoted as: methodName(parameterName: parameterType); return Type

calling object

The object on which an instance method is invoked.

garbage

The object previously referenced by one reference variable when copied to another refernece variable that is no longer referenced by the previous reference variable.

garbage collection

The process by which the java runtime system detects garbage and reclaims the space it occupies.

data field encapsulation

To prevent modifications of data fields, you should declare the fields private, using the private modifier. A private data field cannot be accessed by an object outside the class that defines the private field. However, a client often needs to retrieve and magnify a data field.

State of an object (ALso known as its properties or attributes)

represented by data fields with their current values. A circle object, for example, has a data field radius, which is the property that characterizesna circle . A rectangle object, for example, has the data fields width and height, which are the properties that characterize a rectangle.

object

represents an entity in a real world that cna be distinctly dentified. An object has a unique identity, state and behavior.

setter (or mutator) method

sets a new value to enable a private data field to be accessible.

declare static variable

static int NumberOfObjects;

pass- by- sharing

the object in the method is the same as the object being passed. *See figure 918 on pg. 351.

reference data fields

the this keyword gives us a way to reference the object that invokes an instance method.

Using this to invoke a constructor

the this method can be used to invoke another constructor of the same class. For example, public class Circle{ private double radius; public Circle (double radius){ this.radius=radius; }: The this keyword is used to reference the data field of the object being constructed. public Circle(); this(1.0); the this keyword is used to invoke another constructor. } ... }

Analyze the following code: class test{ private double 1; public test (double i){ this.t(); this.i=i; } public Test(){ System.out.println("Default Constructor"); this910; } public void t(); System.out.println(Invoking t"); } }

this(1) must be called before System.out.println("Default Constructor").

testCircle.java

1. public class TestCircle{ 2. public static void main(String []args); 3. Circle circle1= new Circle(); 4. System.out.println("The area of the circle of radius" 5. + circle1.radius+"is"+circle1.getArea)); 6.circle2= new circle(25); 7. System.out.println("The area of the circle of radius" 8. +circle2.radius+"is'+circle2.getArea()); 9. Circle circle3= new circle(125); 10. System.out.println("The area of the circle of radius" 11. circle3.radius+"is"getArea()); 12. circle2.radius=100; 13.System.out.println("The area of the circle of radius" 14. +circle2.radius+"is"+circle2.getArea()): 15.} 16.} 17.Class Circle{ 18. double radius; 19. circle(); 10. radius=1; 21.} 22. circle(double newRadius){ 23. radius= newRadius; 24.} 25. double getArea(); 26. return radius*radius*Math.PI; 27.} 28. double getPerimeter(){ 29. return 2radius*radius*Math.PI; 3.} 31. void setRadius(double newRadius){ 32. radius= newradius; 33. } 34.} the area of the circlel of radius is 3.141592653589793 The area of teh circle of radius 25.0 is 1963.4954084936207 The area of the circle of radius of 125.0 is 49087.385212340516 Tha area of the circle of radius of 100.0 is 31415.926535897932 * The main class contains the main method(line 3). The new operator is used to create an object from the constructor. newcircle() creates an object with radius1, newCircle(25) creates an object with radius 25 and newCircle(125) creates and object with radius 125. These objects(circle1, circle2, circle3) have different data, but the same methods. Therefore, you can compute their respective areas by using the getArea() mwethod. The data fields can be sccessed via the reference of the object using circle1.radius, circle2.radius and circle3.radius, respectively. The object can invoke its method via the reference of the object using circle1.getArea();, circle2.getArea(); and circle3.getArea();, respectively. These three objects are independent. The radius of circle2 is changes to 100 in line 20. The object's new radius and area are displayed in lines 21 and 22.

reference type

A class is essentially a program defined type. A class is a reference type, which means that a variable of the class type can refereence an instance of the class. The following statement declares the variable myCircle to be of the circle type. circle myCircle; The variable myCircle can reference a circle object. The next statement creates an object and assigns it to myCircle. myCircle= new Circle(); You can rewrite a single statement that combines the declaration of an pbject reference variable, the creation of an object, and the assigining of an object reference variable with the following syntax: Circle myCircle= new circle(2);

no- arg constructor

A class normally provides a constructor without arguements. Such a constructor is called a no- arg constructor.

null pointer exception

A common runtime error that occurs when you invoke a method on a reference variable with a null value. Make sure you assign an object reference to the varialbe before invoking the method throught the reference variable.

which of the following statements are true? A default constructor is provided automatically if no constructors are explicitly declared in the class. the default constructor is a no- arg constructor. At least one constructor must always be defined explicitly. Every class has a default constructor.

A default constructor is provided automatically if no constructors are explicitly declared in the class. The default constructor is a no- arg constructor.

instance method

A method you can onlly invoke upon a specific instance.

Array of objects

Circle[] circleArray= new circle[10]; To initialize CircleArray, you can use a for loop as follows: for(int i=0; i<circleArray.length; i++){ CircleArray[i]= new circle(); } An array object is actually an array of refernce variables. When an array of objects is created using the new operator, each element in the array is a reference variable with a default value of null.

instantation

Creating an instance: Yu can create many instances of a single class.

behavior of an object (aka its actions)

Defined by methods. To nvoke a method of an object is to ask it to perform an action. You may defiine methods getArea(); circle may involve getPerimeter(); for a circle object. A circle object may involve getArea(); to return its area and getPerimeter() too return its perimeter. You can also define the setRadius(radius) method, which a circle object can invoke to change its radius.

null value

If a data field of a reference type does not reference any object, the data field holds a special literal value, null.

hidden variables

If a local variable has the same name as a class's variable, the local varaible takes precedence and the class's variable with the same name is hidden. public class F{ private int x=0; // Instance variable private int y=0; pub;ic F(){ } public void p(){ int x=1; // Local variable System.outprintln("x="+x); system.out.println("y="+y); } } What is the output for f.p() where f is an instance of F? The putput for f.p() is 1 for x and 0 for y. Here's why: * x is declared as a data field with the inintial value of 0 int the class, but it is also declared in the method p() with an initial value of 1. The latter x is referenced in the System.out.println statement. * Y is declared outside the method, but y is accessible inside the method.

package- private (or package- access)

If no visibility modifier is used, then by default, the classes, methds, and data fields are accessible by any class in the same package.

class's variables

Instance and static variables are referred to as the class's varaibles or data fields. A variable defined inside a local method is referred to as a local variable. The scope of a class's variable is the entire class, regardless of where the variables are declared. A class's variables and methods appear in any order in the class. The exception is when a data field is initialized based on a reference to another data field. In such cases, the other field must be declared first.

common design error

It is a common design error to define an instance method that should have been defined as static. For example, the method factorial(int n) should have been defined as static. Wrong Design: public class test{ public int factorial(int n){ int result= 1; for(int i=0; i<=n; i++) result*=i; return result: } } Correct Design: public class Test{ public static void int Factorial(int n){ int result=1; for(int result=1; i<=n; i++) result*=i; return result: } }

instance varaible

a variable that is dependent on a specific instance.

declare constant

constants in a class are shared by objects of the class. For example, the constant PI in the math class is defined as follows: final static double PI= 3.14159265358979323846;

constructing objects using constructors

constructors have 3 peculiarities: 1. a constructor must have the same name as the class itself. 2. constructors do not have a retun type- not even void. 3. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.

the random class

java.util.Random generates random int, long, float and boolean values. java.util.random +Random(): constructs a random object with the current time as its seed. +Random(Seed: long): Constructs a random object with a specified seed. +nextInt() : int: returns a random int value. +nextLong() : long: Returns a random long value. +nextDouble() : double: returns a random double value between 0.0 and 1.0 (excluding 1.0). +nextFloat() : float: returns a random float value between 0.0F and 1.0F (excluding 1.0F). a+nextBoolean() : boolean: Returns a random boolean value. When you create a random object, you have to specify a seed or use the default seed. The no- arg constructor creates a random object using the current elapsed time as seed. If two random objects have the same seed, they will generate identical sequences of numbers.

getter (or accessor) method

makes a private data field accessible.

private modifier

makes methods and data fields accessible from only within its own class.

constructors

methods invoked by classes to create a new object. A constructor can preeform any action, but constructors are designed to perform initializing actions, such as initiaizing the data fields of objects.

invoking methods

nonstatic methods must be inivoked from an object using objectefvar.methodName(arguements).(e.g., myCircle.getArea()).

reference variable

objects are accessed via their reference variables, which contian references to the objects. Such variables are declared using the following syntax: className objectOfRefVar;

boolean accessor

public returntype getPropertyName() If the returntype is boolena, the getter method should be defined as follows by the convention: public boolean isPropertyName(); A setter method has the following signature: public void setPropertyName(dataType propertyValue)


Related study sets

MANA3335 MindTap Learn It: Chapter 15: Managing Operations, Quality, and Productivity

View Set

French - Unit 4 Test (Partie Orale)

View Set

Hawaii Supreme Court Trivia Set 7

View Set

Chapter 11 Principles of Radiographic Imaging

View Set

P&P1 - Review questions for resting membrane potential and action potentials - Huang

View Set

Injectable Medication Administration Pretest

View Set

Prelude 4: Music as Order and Logic

View Set

Abnormal Psychology - Chapter 10

View Set