CS 302 Chapter 9

¡Supera tus tareas y exámenes ahora con Quizwiz!

Pass-by-sharing

Pass-by-sharing is when the object referenced in the method is the same as the object being passed Pg. 348

Constructor Syntax

Uses UML Syntax: ClassName(parameter name: parameterType) Ex: Circle(double newRadius) { }

Data Field syntax

Uses UML Syntax: dataFieldname: dataFieldType Ex: double radius = 1; Pg. 323

Note:

Usually you create an object and assign it to a variable, and then later you can use the variable to reference the object. Occasionally an object does not need to be referenced later. In this case you can create an object without explicitly assigning a variable using the syntax: new Classname() Ex: new Circle() or System.out,print("Area is " + new Circle(5).getArea()); Pg. 331

Constructors are used to create objects

To construct an object from a class invoke a constructor of the class using the new operator. Ex: new ClassName(arguments); new Circle() creates an object of the circle class using the first constructor defined in the Circle class that has no arguments New Circle(25) creates an object using a different (most likely second constructor) defined in the circle class that has arguments of type int or double Pg. 329

Array of objects

An array can hold objects as well as primitive data types Example: the following syntax declares an creates an array of 10 circle objects Syntax: ClassName[] arrayRefVar = new ClassName [size of the array]; Circle[] circleArray = new Circle[10]; Note: when an array of objects is created using the word new, each element in the array is set to the value of null. Pg. 351

Hidden varaibles

if a local variable has the same name as a class's variable, the local variable takes precedence and the class's variable with the same name is then hidden. A hidden static variable can be accessd by using the syntax: ClassName.staticVariable reference A hidden instance variable can be accessed by using the keyword this Pg. 355

Note on design guide Pg. 341

A variable or method that is dependent on a specific instance of the class should be an instance variable or method A variable or a method that is not dependent on a specific instance of the class should be a static variable or method. The main method is static and can be directly invoked from a class Pg. 341

A visibility modifier

A visibility modifier specifies how data fields and methods in a class can be accessed from outside the class. there is no restriction on accessing data fields and methods from inside the class Ex: Something that is defined inside its own class can access its private members. Something that is not defined within its own class cannot access its private members Pg. 343

An array of objects is actually

An array of objects is actually an array of reference variables. So invoking arrayRefVar[i].getArea() involves to levels of referenceing arrayRefVar references the entire array of objects arrayRefVar[i] references the object at index i. Note: when you use new to create an array of objects, each element is set to the value of null. If you try to invoke a method on this you will get a NullPointerException Pg. 351

Note on instance methods

An instance method can invoke an instance or static method and access an instance or static data field.

Note on object reference variables

An object reference variable that appears to hold an object actually contains a reference to that object. Strictly speaking, an object reference variable and an object are different but most of the time the distinction can be ingnored Pg. 330

Accessing Objects Via reference variables

An objects data and methods can be accessed through the (.) operator via the objects reference variable Classname objectReferenceVariable = new Classname(arguments); Example: Circle myCircle = new Circle(); myCircle holds a reference to a specific circle object (instance) of the circle class A referernce to newly created objects are allocated space in memory. They can be accessed via reference variables Pg. 330

Accessing an Objects Data and Methods

An objects members refers to its data fields and methods. After an object is created, its data can be accessed, and its methods can be invoked using a dot operator (.) also known as a member access operator Pg. 330

Note about arrays

Arrays are treated as objects in java. Arrays are created using the new operator. An array variable is actually a variable that contains a reference to an array Pg. 330

Class

Objects of the same type are defined using a common class A class is a template, blueprint or contract the defines what an objects data fields or methods will be. A class provides constructors for creating objects and methods for manipulating them An object is an Instance of a class. You can create many instances of a class creating an instance is referred to as INSTANTIATION A class is also a data type, you can use it to declare reference variables. Note: object and instance are used interchangeably Pg. 323

Passing Objects to methods

Passing an object to a method is to pass the reference of the object You can pass objects to methods. Like passing an array, passing an object is actually passing the reference of the object. Pg. 347

Example of passing an object to a method Pg. 347

PrintCircle(myCircle); When we pass an object, we are actually passing the reference to the particular object using the objects reference variable. In this case we are passing (myCircle) to the method print circle. We are passing the reference of the object (remember myCircle is the object reference variable for the Circle object, Circle myCircle= new Circle;) Pg. 347

Accessing hidden instance variable by using this

Public class F { private int i = 5; private static double k = 0; public void setI(int i) { this.i = i; } public static void setK(double k){ F.k = k; } The keyword this gives us a way to reference the object that invokes an instance method. To invoke fi.1.setI(10).this.i = i is executed, which assigns the value of the parameter i to the data field i of this calling object f1. The keyword this refers to the object that invokes the instance method setI The line F.k = k means that the value in the parameter k is assigned to the static data field k of the class, which is shared by all objects of the class Pg. 357

Setter and getter syntax

Setter method Syntax: public void setName(dataType datafieldName) Ex: public void setRadius(double newRadius) Syntax for getter method: public returnType getName(); public double getRadius() If the return type is boolean the getter methods syntax is: public boolean isDataFieldName() public boolean isPropertyName()

Static methods and static data

Static methods (ex: getNumberOfObjects()) and static data (ex: numberOfObjects) can be accessed from a reference variable from their class name. Note static variables and static methods can be accessed without creating objects Pg. 339

Static variables + static methods

Static variables are shared by all objects of the class. A static method cannot access instance members of the class. It is also a method can be invoked without using instances Pg. 337

Syntax for declaring a static variable and static method

Syntax for declaring static variable: static dataType name static int numberOfObjects Syntax for declaring a static method: static dataType getName(){ return name } static int getNumberOfObjects(){ return numberOfObjects; } The return type for the method must match the dataType. In this case our dataType is int, so we must return a value of type int Pg. 337

Behavior of an object

The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an object is to ask the object to perform an action Ex: you may define methods named getArea() and getPerimeter() for circle objects. A circle object may invoke getArea() to return its area and getPerimeter t0 to return its perimeter Pg. 323

How to access the data fields

The data fields can be accessed via the reference of the object using objectReferenceVariable.dataField Ex: circle1.radius Pg. 326

Data fields can be of reference types

The data fields can be of reference types Ex: class Student{ String name; int age; boolean isScienceMajor; char gender; } Pg. 331

Dot operator (.)

The dot operator is used to access members of that object through its reference variable Known as a member access operator: Syntax: objectRefVar.dataField references a data field in an object objectRefVar.method(arguments) invokes a method on that object Ex: myCircle, and myCircle.getArea() invokes the get area method on myCircle Methods are invoked as operations on objects Pg. 331

The this reference

The keyword this refers to the object itself. It can also be used inside of a constructor to invoke another constructor of the same class. The keyword this is the name of a reference that an object can use to refer to itself. You can use the this keyword to reference the object's instance members Pg. 356

Invoking a method via referencing

The object can invoke its method via the reference of the object using objectReferenceVariable.method Ex: circle1.getArea() Pg. 326

Note on the private + public modifiers

The private modifier applies only to the MEMBERS of a class. The public modifier can apply to a class or members of a class. Using modifiers public and private on local variables would cause a compiler error. YOU CANNOT USE PUBLIC AND PRIVATE MODIFIERS ON LOCAL VARIABLES Local variables are variables inside of methods and loops. Pg. 344

Scope of variables

The scope of instance and static variables is the entire class, regardless of where the variables are declared Pg. 355

Object creation

The syntax for creating an object: classname objectReferenceVariable = new classname(arguments if any); Ex: TV tv1 = new TV(arguments if any) Pg. 328

Using this to invoke a constructor

The this keyword can be used to invoke a constructor of the same class Ex: rewrite the circle class public class Circle { private double radius; public Circle(double radius){ this.radius = radius } The this keyword is used to reference the hidden data field radius of the object being constructed public Circle(){ this(1.0) } The this keyword is used to invoke another constructor Pg. 357

Using this to reference hidden data fields

The this keyword can be used to reference a class's hidden data fields For example: a data-field name is often used as the parameter name is a setter method for the data field. In this case the data field is hidden in the setter method. You need to reference the hidden data-field name in the method in order to set a new value to it. Pg. 356

Creating an object and assigning its reference to an objectRefVar

This statement creates an object and assigns its reference to myCircle Ex: Circle myCircle = new Circle(); Pg. 330

Declaring a static variable or defining a static method

To declare a static variable or define a static method, put the modifier static in the variable or method declaration. Ex: we create a static varaible called numberOfObjects to count the number of objects that are created in the circle class Syntax for declaring a static variable: static dataType nameOfVariable static int numberOfObjects; Pg. 337

Getter and Setter methods

To enable a private data field to be updated provide a setter method to set a new value. Also referred to as a mutator A getter method returns the values of a private data field. A getter method is also called as an accessor. Pg. 345

how to prevent direct modifications of data fields

To prevent direct modifications of data fields, you should declare data fields private, using the private modifier. The process of doing this is called data field encapsulation Pg. 344

UML

Unified modeling language. Class templates and objects can be illustrated using this UML. Pg. 323

Note on invoking static methods and variables

Use ClassName.methodName(arguments) to invoke a static method, and ClassName.staticVaraible to access a static variable. This improves readability because this makes the static method easy to spot Pg. 340

Visibility modifiers

Visibility modifiers can be used to specify the visibility of a class and its members Pg. 342

Note

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. This is why you need to use a four loop to initialize each index of the array with a reference to an object, or else if you try to invoke a method you will get a NullPointerException Pg. 351

Passing an argument of primitive type vs. passing an argument of reference value

When passing an argument of primitive data type, the value of the object is passed. When passing an argument of a reference type, the reference of the object is passed. Ex: c contains the reference for the object that is also reference to myCircle. Therefore changing the properties of the object through c inside the printAreas method has the same effect as doing so outside the method through the variable myCircle. Pg. 348

Primitive type variables

When you assign one variable to another, the other variable is set to the same value For a variable of the primitive type, the real value of one variable is assigned to the other variable. A variable of primitive type holds a value of the primitive type Ex: int i = 1; i is set to the value of 1 Pg. 332

Creation of a Random object

When you create a random object, you have to specify a seed or use the default seed. A seed is a number used to initialize a random number generator. The no-arg constructor creates a random object using the current elapsed time as its seed Pg. 335

Declaring a class's variables

You can declare a class's variables only once, but you can declare the same variable name in a method many times in different non-nesting blocks. Pg. 355

Immutable class

You can define immutable classes to create immutable objects. The contents of an immutable objects cannot be changed. For a class to be immutable it must meet 3 requirements: 1. all data fields must be private 2. there cannot be any mutator methods for the data fields 3. no accessor methods can return a reference to a data field that it mutable Pg. 354

Public visibility modifier

You can use the public visibility modifier for classes, methods, and data fields to denote that they can be accessed from any other classes. If no visibility modifier is used then by default the classes, methods and data fields are accessible by any class in the same package. This is known as package-private or package-access. The public modifier enables unrestricted access Pg. 342

NullPointerException

is a common runtime error. It occurs when you invoke a method on a reference variable with a null value. Make sure you assign an object reference to the variable before invoking the method through the reference variable Pg. 331

Object

represents an entity in the real world that can be distinctly identified. An object is an instance of a class. Pg. 322

Data fields

the state of the object (also known as its properties or attributes) is represented by data fields with their current values java uses variables to define data fields Ex: A circle object has a data field radius which is the property that characterizes the circle Ex: a rectangle object has the data fields width and height which are the properties that characterize a rectangle Pg. 323

How to initialize an array of objects

use a for loop like this for(int i = 0; i < arrayReferenceVariable.length; i++){ arrayReferenceVariable[i] = new Circle(); } Pg. 351

Note on static methods

A static method can invoke a static method and access a static variable; however, a static method CANNOT invoke an instance method or access an instance data field, since static methods and static data fields don't belong to a particular object. Pg. 340

Instance methods and Instance data

Instance methods (ex: getArea()), and instance data (ex: radius) belong to instances and can only be used after the instances are created. They are accessed via a reference variable (objectReferenceVariable) Pg. 339

Reference type

A class is essentially a programmer-defined type. A class is a reference type, which means that a variable of the class type can reference an instance of the class. Ex: this statement declares the variable myCircle to be of the Circle type Circle myCircle The variable myCircle can reference a circle object (because according to the syntax myCircle = objectReferenceVariable, which references the location in memory) Pg. 330

No arg constructor

A class normally provides a constructor without arguments Ex: Circle() Such a constructor is called a no-arg or no-argument constructor A class may be defined without constructors. In this case of the circle, a public no-arg constructor with an empty class body is defined in the class. Pg. 329

Class's variables

A class's variables and methods can appear in any order in the class. The exception is when a data field is initialized based on the reference of another data field. In such cases the other data field must be declared first. For consistency declare data fields at the beginning of the class Pg. 355

Constructing Objects using Constructors

A constructor is invoked to create an object using the new operator Constructors are special kinds of methods. They have three peculiarities 1. A constructor must have the same name as the class itself 2. Constructors do not have a return type, not even void 3. Constructors are invoked using the new operator when an object is create Constructors play the role of initializing objects The constructor has the exact same name as its defining class Pg. 329

Default constructor

A default constructor is provided automatically only if NO CONSTRUCTORS ARE EXPLICITLY DEFINED IN THE CLASS

Local Variable

A local variable is a variable defined inside a method Pg. 355

A private field

A private field cannot be access by an object from outside the class that defines the private field. However, to retrieve the and modify the data you need a getter method to get the data and a setter method to to set a new value Pg. 345

Static methods

Cannot access instance members of the class Are supported by java Static methods can be called without creating an instance of the class. Syntax for declaring a static method: static dataType nameOfMethod(arguments){ } static int numberOfObjects(){ } Pg. 337

Classes

Classes are definitions for objects and objects are created from classes. Note you can put two classes into a file but only one class can be the public class. The public class must have the same name as the filename Pg. 324

Constants

Constants in a class are shared by all objects of the class. Thus constants should be declared using the following syntax: final static dataType NAME(in all caps) = value; (of the same dataType) final static double PI = 3.1415; Pg. 338

Constructors

Constructors are special methods that are called when an object is instantiated. A constructor initializes the created instance. Typically the constructor initializes the fields of the object that need initialization. They can perform any action, but constructors are designed to perform initializing actions, such as initializing the data fields of objects. Say there were 2 constructors: Circle(){ //No-arg constructor radius = 1; //data field radius is initalized to 1 } Circle(int newRadius){ // argument of type int called newRadius radius = newRadius; // datafield radius is initalized } So if an object was created, the term "new" with no arguments it would invoke the constructor with the same type of arguments (in this case the constructor with no arguments) So if an object was created with arguments of type int, Ex: Circle myCircle = new Circle(25), the term "new" would invoke the constructor with the same arguments (in this case the second constructor with the arguments of type int Pg 323

Overloading a constructor

Constructors can be overloaded When you overload a constructor you give it the same name but multiple constructors can have the same name but different signatures This makes it easier to construct objects with different initial data values Ex: Circle(double newRadius){ //initalize dataField } Circle(int newRadius){ //initalize dataField } When an object is created with arguments of type double, the first constructor is used. When an object is created with arguments of type int, the second constructor is used. The type of constructor that is used is dependent on the type of arguments that are used in the creation of the object. Pg. 329

Differences between Variables of primitive types and Reference types

Every variable represents a memory location that holds a value. When you declare a variable you are telling the compiler what type of value a variable can hold When you assign one variable to another, the other variable is set to the same value Pg. 332

Using this to reference the object's instance members

Ex: Public double getArea(){ return this.radius * this.radius * MATH.PI; } In this code this is used to reference the object's radius and invokes the getArea(0 method explicitly. The this reference is usually omitted; however the this reference is needed to reference hidden data fields or invoke an overloaded constructor Pg. 356

Reference variable types

For a variable of a reference type, the real value of one variable is assigned to the other variable. A variable of a reference type holds a reference to where an object is stored in memory. Circle c, holds a reference to the memory location of c. This is the reason why the objectReferenceVariable is called the objectReferenceVariable. It is a variable that holds a reference to the memory location of an object Pg. 332

Reference variables and Reference types

Objects are accessed via the objects reference variable, which contain references to the objects. Such variables are declared using the following syntax: ClassName objectReferenceVariable; An object reference variable appears to hold an object, but it actually contains a reference to that object Pg. 330

Instance variables + instance methods

For example looking at the circle class, the data field radius is referred to as an instance variable because it is dependent on a specific instance. An instance variable belongs to the instance of a class. It is usually associated with individual instances For the same reason, the method getArea() is referred to as an instance method because you can invoke it only on a specific instance. The object on which an instance method is invoked is called a calling object Ex: if circle1 had a radius of 2, and circle2 had a radius of 3 if you did circle2.getRadius() you would get 3, and if you did circle1.getRadius() you would get 2. In this case the data field radius is dependent on the specific instance that is created. It is not the same for all instances of a class Same thing goes with instance methods. If you call a getArea method on two objects with different radii, you will get two different answers, because the getArea() method in this case is dependent on the dataFields of the specific instance that it references using the syntax objectReferenceVariable.getArea() Pg. 331

Instance Variable

Going back to the circle class, the data field radius is known as an instance variable. An instance variable is tied to a specific instance of the class; it is not shared among objects of the same class. Ex: ClassName objectRefVar = new ClassName(arguments) Circle circle1 = new Circle(); //constructor with no arguments would be invoked Circle circle2 = new Circle(25); // constructor of the same type of argument (int in this case) would be invoked The radius here (which is the argument) in circle1 is independent of the radius in circle2, and is stored in a different memory location. However, if we change circle1's radius this doesn't affect circle2's radius because the radii are instance variables and they are tied to specific instances in the class, and it is not shared among other instances of the class. Pg. 337

If a data value of a reference type does not reference any object

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

Static variables (also known as class variables)

If you want all the instances of a class to share data, use static variable, also known as class variables. Static variables store values for the variables in a common memory location If one object changes the value of a static variable, all objects of the same class are affected. Java supports static methods as well as static variables. Pg. 337

Instance and Static variables in a class

Instance and static variables in a class are referred to as the class's variables or data fields. The scope of a class's variables is the entire class, regardless of where the variables are declared Pg. 355

Pass-by-value

Java only uses one mode of passing arguments and that is pass-by-value. All parameters are passed to methods using pass-by-value Ex on Pg. 347: printCircle(myCircle), the value of myCircle is passed to the printCircle method. The value (myCircle) is a reference to a Circle object Pg. 347

Private visibility modifier

Java provides the private visibility modifier. The private visibility modifier makes methods and data fields accessible only from within its own class. The private modifier restricts access to its defining class. Pg. 343

Note on this

Java requires that the this(arg-list) statement appears first in the constructor before any other executable statements Pg. 357

new operator

Like when creating an array, the new operator is used to create an object from the constructor. You use the new operator to create and object Ex: new SimpleCircle() creates an object with a certain radius Pg.326

Data Field Encapsulation

Making data fields private protects data and makes the class easy to maintain. Data field encapsulation is good for two reasons: 1. Data can be tampered with. For example a variable could be mistakenly set to a arbitrary value. Data field encapsulation can prevent this 2. Classes can become difficult to maintain and are vulnerable to bugs. You can use data fields encapsulation to make it easier to maintain classes and make them less vulnerable to bugs Pg. 344

The random class

Math.Random() obtains a random double value between 0.0 and 1.0 (excluding 1.0). Another way to generate random numbers is to use the java.util.random class, which can generate an int, long, double, float and boolean value Pg. 335

Example 9.6 on Pg. 338

Method getNumberOfObjects() in the class CircleWithStaticMembers, is a static method. The main method is also static Pg. 338

What is an what is not a constructor

Not a constructor: public void Circle(){ } While it has the same name it is not a constructor because one of the rules of a constructor is that they do not have a return type. Not even void. This is actually a method A constuctor: Circle(){ //data fields; } This right here is a no argument constructor. While it has no arguments within the parenthesis it follows all three rules. Same name as class, no return type (not even void). This is referred to as a no-arg or no-argument constructor A Constructor Circle(double radius){ //data field; } This right here is a constructor with a single argument, radius. This is a valid constructor because it follows all three rules. No return type (not even void), same name as class. Pg. 329

Math class

Note all of the methods in the math class are static Pg. 338

Null

Null is a literal just like true or false. While true and false are Boolean literals, null is a literal fora reference type. The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and \u0000 for a char type. However, java assigns no default value to a local variable inside a method Pg. 331

Declaration, and creation of an object in a single statement

You can write a single statement that combines the declaration of an object reference variable. the creation of an object, and the assigning of an object reference to the variable with the following Syntax: ClassName objectRefVar = new ClassName(); Ex: Circle myCircle = new Circle(); The variable myCircle holds reference to a circle object Here this example is correct becuase the className is the same (Circle), and the objectRefVar (myCircle) holds the reference to the circle object. The new creates a new Circle object Pg. 330


Conjuntos de estudio relacionados

Football Basics - PE Participation Skills

View Set

Cognitive Psychology Chapter 4 Quiz

View Set

chapter 57 mangement of patient with female reproductive dirorder

View Set

Module 41. Anxiety Disorders, Ocd, And Ptsd

View Set

chapter 3 - policy riders, provisions, options, and exclusions

View Set