0% found this document useful (0 votes)
110 views

Chapter 2: Class and Objects

This document summarizes key concepts about classes and objects in object-oriented programming: 1) Objects represent real-world entities with state (attributes) and behavior (actions). Classes define a blueprint for objects of a certain type. 2) Classes contain data fields (instance variables) to store an object's state, and methods to define its behaviors. Encapsulation combines an object's data and methods into a single unit. 3) Keywords like public, private, and static determine access levels and scope. Methods can be instance methods belonging to objects or static methods belonging to the class. Method overloading allows multiple methods with the same name but different parameters.

Uploaded by

Aditya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Chapter 2: Class and Objects

This document summarizes key concepts about classes and objects in object-oriented programming: 1) Objects represent real-world entities with state (attributes) and behavior (actions). Classes define a blueprint for objects of a certain type. 2) Classes contain data fields (instance variables) to store an object's state, and methods to define its behaviors. Encapsulation combines an object's data and methods into a single unit. 3) Keywords like public, private, and static determine access levels and scope. Methods can be instance methods belonging to objects or static methods belonging to the class. Method overloading allows multiple methods with the same name but different parameters.

Uploaded by

Aditya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Chapter 2: Class and Objects

What are Objects?


Objects are simply representations of some real world object that is being used in the
program. Objects can be characterized by their state and behavior.

State: Different attributes of the said object.

Behavior: Essentially different actions that can be applied to the object.

You can call an object by setting a variable to that object called an "Object Reference."

What are Classes?


A software blueprint for implemented objects of a given type.

A class describes the general "layout" of a certain type of object. Then, individual,
specific objects can be created as part of a class. An object is an instance of a class.

Some Vocabulary:
Data Fields or Instance Variables: Where the current state of an object is stored,
essentially that object's attributes.

Methods: Provide both the behaviors exhibited by the object and the operations that
manipulate the object.

Encapsulation: Combining and object's data and methods into a single unit called a
class.

Public, Private, Static, and Other Keywords:


Public: This just means that the public methods in one class can be accessed inside of
another class. A public class, in addition, means that that class can be used or
referenced in another class and outside of its own package.

A public method, when referenced in another class's main code, it must be


referenced from within the class. Assume there is a public class Example, which has
a public method BooleanFinder. In order to access BooleanFinder in another class
OtherClass, it can be called as Example.BooleanFinder(args);

Private: Allows for restriction of access known as information hiding.

Chapter 2 Class and Objects 1


When there is a private instance variable or private method in one class, that
information of method is not privy to being called in other classes. Other classes
cannot access that data or program.

Static: A static variable or method, essentially, belongs not to a particular instance of the
class, but actually to the class itself. This means that, for example, a static method can
be called without refernce to an object.

Thus, if there is an add(a, b) function, it can be called within the same class as
add(a, b) instead of the following code below:

public class BankAccount


{
public static void main(String[] args) {
BankAccount account1 = new BankAccount();
account1.add(4, 5);
}

/* Methods */
public add(int a, int b) {
int c = a + b;
System.out.print(c);
}
}

Methods:
Headers:
All method headers are created in this format: public void withdraw String password,
double amount) {}

In this example, public is an access specifier. This is because it decides who gets
access to the method.

Next, the void is the return type. It specifies what kind of output the method gives.

Third, the withdraw is simply the method name.

Finally, the String password, double amount) is just the parameter list.

Constructors
Constructors create an object of the class. The constructor's name is always the same
as the name of the class. The reason for this is because it specifies the creation of an
object of the class. It has no return type.

Chapter 2 Class and Objects 2


There are two types of constructors:

 A default constructor has no arguments. In addition, it has no return type. It


provides reasonable initial values for an object. The "name" of the object that is
being created can be thought of as a reference to the actual object.

 Another type of constructor actually has parameters, and uses the information
gained from the parameters' inputs in order to set the instance variables of a
certain object to the values of those parameters.

 Important to Note: "b" and "c" in the code snippets below are NOT the objects
themselves. Instead they are simply references to the objects.

/* Default Constructor Follows */ /* Constructor with Parameters Follows */

public BankAccount() { public BankAccount(String acctPassword,


password = ""; double acctBalance) {
balance = 0.0; password = acctPassword;
} balance = acctBalance;
}
BankAccount b = new BankAccount(); BankAccount c = new BankAccount("KevinC", 800.00);

Accessors
An accessor method accesses a class object without altering the object. It simply
returns some information about the object.

It, too, follows the method header format, and this time, unlike a constructor, it actually
has a return type.

Dot Operator:

The dot operator ( . operator) indicates that getBalance() is a method of the class to
which b1 and b2 belong, so thus, you can state, b1.getBalance() or b2.getBalance()

Mutators
A mutator method changes the state of an object by modifying at least one of its
instance variables.

It has parameters, and inside of a mutator, there is usually some kind of function.
Sometimes, it is a for, if, if - else, while, etc. function to implement and change one of the
instance variables of that class.

Chapter 2 Class and Objects 3


Static Methods vs. Instance Methods
Static Method
Static Method: This type of method operates on the entirety of the class. It can be
called without the use of the dot operator following the object name, and simply
"belongs" to the class itself. It is also called a class method.

Or, the dot operator can follow the class name, preceding the method name. This works
as well.

Instance Method

Instance Method: This is a type of method that works, and "belongs" to an instance of a
class. Thus, it works and "belongs" to an object. In order to call an instance method, you
must use the dot operator following the object name.

The main method must always be static because it is located at the start of execution of
the program, and is at a time where there have not been any objects created. Thus, the
main method must always be static.

Method Overloading
Overloaded Methods are two or more methods in the same class that have the same
name but different parameter lists.

Overloaded Constructors provide various different means of creating objects. Although


they have the same name, they are overloaded because of the different parameter lists.

public class DoOperations {


public int product(int n) {return n*n}
public double product(double x) {return x*x}
public double product(int x, int y) {return x * y}
}

/** The signatures of these functions do not care about return types, only about the parameter list
and the function name. That is all that defines the signatures. The signature list follows below */
product(int);
product(double);
product(int, int);

Scope

Chapter 2 Class and Objects 4


The region in which that variable or method is visible and can be accessed.

The instance variables, static variables, and methods of a class belong to that class's
scope.

A certain component's scope starts at the first brace - { - and ends at the second brace
-}-.

It is important to note that a local variable, which is defined inside of a method, has
a scope of that method. Its scope, AKA area of operation, extends from the first
brace to the second brace of that method's definition.

Local Variables take precedence over instance variables with the same name. However,
doing this is bad practice, and creates ambiguity for the programmer.

The "This" Keyword


When an instance method is called for a particular object, the implicit parameter is
going to be the object itself. Let's say you want to call the object itself, we use the "This"
keyword.

Example: Let's say there is a method call obj.doSomething("Mary", num). Here, "Mary,"
and num, are explicit parameters while obj is an implicit parameter.

Example: For example, you can use this to print the object itself. You can say
System.out.println(this) and it will call the toString(); function, which will print the object.

Example: Third example, let's say you would like to simply create a method called
"deposit" that adds to a bank account's balance. If the bank account has an instance
variable called "balance," the method's statements do not need to be this.balance +=
amount;, and instead, they can be balance += amount;. The use of "this" here is
unneeded.

Example: Let's assume that you are creating a local variable inside of a constructor, but
that local variable has the same name as an instance variable defined at the beginning of
the class. This is bad practice, but what you could do to handle it is use the keyword
"this." Look at the following code segment:

private int num;


private int denom;

public Rational(int num, int denom)


{
this.num = num;
this.denom = denom;
}

Chapter 2 Class and Objects 5


Reference vs. Primitive Data Types
Primitive Data Types: Include double, int, char, boolean. In a primitive data type, for each
variable, a memory slot is created that stores the data inside of itself. For example, int
num1 = 3; creates a memory slot called num1, which stores the data of an int with value
3.

Reference Data Types: Include objects, arrays. In a reference data type, a variable data
slot is created, but the actual data is not stored there. Instead, a reference, or simply
the address, for the data is stored. Thus, for example, in the statement Date d = new
Date(2, 17, 1948; the memory slot d is being created, which does not store the new
object, but stores the address for the object d.

This means that you can have multiple variables referring to the same object or
array.

Date birthday = d; does not create a clone object of d called object birthday. It,
instead, creates a memory slot of birthday that refers to the object d.

In order to create the clone, the new keyword must be used, and the object -
declaring process must go through. For example, the programmer can say Date
birthday = new Date(d.getMonth(), d.getDay(), d.getYear();

The Null Reference


The declaration BankAccount b; has a problem. The problem is that although it attempts
to create a new object with the reference variable b, it does not use the new keyword to
initialize it.

This type of uninitialized object variable is called a null reference or null pointer. Any
attempt to invoke an instance method with a null reference may cause the program to
terminate with a NullPointerException.

Different Errors with Relation to Null References:

Fail to initialize a local variable: This will lead to the compiler giving a compile-time
error.

Fail to initialize an instance variable of a class: The compiler will provide reasonable
default values, such as 0 for int and false for booleans.

Fail to initialize a reference instance variable of a class: Compiler will set it to null. If
invoked, it will result in a NullPointerException.

Chapter 2 Class and Objects 6


Method Parameters: Formal vs. Actual Parameters
Formal Parameters: When a method is created, the parameters in the method parameter
list are given variable names. These are different from the instance variables declared at
the beginning of the class. These are the formal parameters.

Actual Parameters: When a method is actually called, the method call will have variables
in the parameter list that are the actual parameters.

Passing Primitive Types as Parameters


Passed by Value: Essentially, what this means is that when primitive types are called in a
method, a new memory slot is allocated for each parameter. Essentially, this means that
any changes made to the parameters will not affect the values of the arguments in the
calling program.

When the method is exited, the local memory slots of the parameters are erased.

Passing Objects as Parameters:


Object references are also passed by value. This means that still, changes made to the
parameters will not change the value of the matching arguments.

Thus, it means that you cannot repalce an object with another one, as you can't change
the reference that was passed. However, you can change and affect the object being
dealt with, and its state, in many cases.

Example: A method can be called that has the parameters of an object. Thus, now, there
is a local reference to the object. Then, the object can be manipulated or changed by
this local reference. When all is said and done, the local reference, as well as all the local
parameters, are deleted. However, the changes on the object are still there.

Example: Sometimes, a programmer may try to create a reference to a certain object


using a method. For instance (haha get the joke), one example is if there are two
BankAccount objects, and the programmer wants to create a reference called
betterBankAccount that has an address to the better one. They may create a null
BankAccount object, that through the method, will set a local variable in the method to
reference the better account.

However, this will not work, because after the method is over, the local variable set
to the better BankAccount object will disappear. In order to fix this, the programmer
needs to:

Chapter 2 Class and Objects 7


Have the function return the address in that local variable, and set it equal to the
variable the programmer wants to refer to the betterBankAccount. Look at pages
105 - 110 for information and illustrations for this example, Barrons Computer
Science A.

Chapter 2 Class and Objects 8

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy