0% found this document useful (0 votes)
16 views13 pages

Exam Notes2

Uploaded by

chumbucket2050
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views13 pages

Exam Notes2

Uploaded by

chumbucket2050
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

LECTURE1:

Class overview
Designing a system in programming covers the following components/sub-components:
class = group of objects similar in terms of functionality or status.
object = an individual component.
State = value of a property of an object
things to do = methods the object has
relationships = data structures.

example:
- class = car
- object = your car
- state = color, model, effeciency, fuel, mileage.
- methods = star, stop, accelerate, slow down...etc
- relationships = ahead of other cars, behind other cars? ...etc
A class is made up of objects, these objects have:
different fields (variable, data types or data values or in other words, memory
references).
different methods (basically what gives an object functionality or what changes the
objects fields or fields values or simply provide info on the objects state).
Types of methods (there is 4 buts lets look at 2 for now (mutator branches into around 3
more hence 4 in total)):
- mutator: changing the object state.
- assessor: provide info on the object state.

Constructors and using objects.


To create objects, we also need a special type of mutator methods called the constructor,
this constructor forms an object from a class that allows you to call all the non-static
functions. the mutator also could assign values/properties to the object as an initial state.
the constructor has the same name as the class, it can take parameters but it can not
return any values. (you have to form the method outside the main method just like any
other method)
- for example we want to make a constructor that creates bank accounts, it will give an
option to deposit an initial amount in doubles.

public class BankAccount{


//lets create the constructor
public BankAccount(double initialAmount){
//we need a variable to store the initialAmount in.
this.balance = initialAmount;
}
//make the variable private so no one outside the class can access it or
modify it.
private double balance = 0.0;
}

this constructor will create an object with a specific initial deposit, for example if we wanna
use the constructor to make an object we are going to do this:

/*ClassName anyNameForTheObject = new ConstructorName(parametersIfNeeded)*/


BankAccount mrGonzalez = new BankAccount(2.0);

now we have an object from BankAccount class, it can be used to call all its methods, for
example (lets make some methods first):

public class BankAccount{


private double balance = 0.0;
//this one is going to be a global variable, so it is static
private static double bankLiquidity = 0.0;
//lets create the constructor
public BankAccount(double initialAmount){
//we need a variable to store the initialAmount in.
this.balance = initialAmount;
bankLiquidity+=initialAmount;
}
//this method will add money to the balance of the specific object the
method is called on (notice how we don't have static)
public void deposit(double amount){
this.balance += amount;
bankLiquidity+=amount;
}
//this method will remove a specific amount of money from the spefici
object, also not static
public void withdraw(double amount){
this.balance -= amount;
bankLiquidity -= amount;
}
//this method will tell us how much balance the object has, also not static
public double showBalance(){
return this.balance
}
//this method will show all the money the bank has accross all account, it
is static
public static double showBankLiquidity(){
return bankLiquidity;
}

now that we have some methods, we can call them either directly on the objects or on the
class depending on if they are static or not (static on class, non-static on object):

BankAccount mrGonzalez = new BankAccount(2.0);


mrGonzalez.deposit(5.0);
mrGonzalez.withdraw(10.0);
double balanceGonzalez = mrGonzalez.showBalance();
System.out.print(balanceGonzalez); //bro has -3 aura
double bankLiquidityBalance = BankAccount.showBankLiquidity(); //mr gonzalez broke
the bank bro, not enough pesos.
System.out.print(bankLiquidityBalance); //that is what u get when you only have one
customer, and he is mexican (pesos aint that powerful bro).

objects allow us to access non static (public fields if outside the class) of a class.
for static ones, we dont need an object, the class name alone suffices.
summary (constructors):
1. Has the same name as the class
2. Is usually public
3. Creates an object in a class
4. initializes instance variables for each object (every declaration of the constructor
initializes an instance variable)
5. Don't usually return any value of any type.
6. structure: <\access specifier><class name>(<parameter(s)>){method body}
7. Every class has a constructor, if you don't write one java will make an invisible one by
default that only creates the object without any special operations or fields or values
or properties.
8. you can have more than one constructor.
9. They should mostly assign values to the object’s instance fields
10. If it doesn't assign a value, then the default is 0.0 for numerical and null for string
(don't bet your life on this)

Fields, Methods, and anything related


Access specifier
it is specified before the data type of even the name of the field/method and it can be:
public int somePublic; // other classes can access them
private int somePrivate; // other classes can not access them
protected int someProtected; // only classes in the same
//package and subclasses can access them.
int someDefault;
/*default*/ // you dont specify anything when you want to specify default, can only
be accessed in the same package and not by subclasses.

same class same package subclass universal


private X
public X X X X
protecred X X X
default X X

Variable type/Return type (data type)


In java we have two types of data, reference vs Non-reference (primitive)

non-reference variables (NRV) are the ones we are used to, the primitive variables: {short,
byte, int, double, float, long,boolean, char}
reference variables (RV) are the variables that refer to objects such as the variables we
declare to store a newly created object from a class: Scanner input = new
Scanner(System.in) . they dont hold the objects they just refer to the objects.
if you copy value from a NRV to another NRV variable, changing the first wont affect the
other because the have two separate values 2nd variable just copied the first and that is it,
example:
double one = 1.0;
double two = one;
one++;
System.out.println(one); //will print 2.0
System.out.println(two); //will print 1.0

With RV however it is a different story; since you are only referencing with the variables no
values are held so when you make two RVs and copy the 1st to 2nd, change the value for
1st will change it for the second as well since you are changing the value of the object
referenced and since both variables point to the same object value of both will change,
example:

Car car1 = new Car(/*fuel:*/ 500); //references a new segment in the memory, les
call that segment 69
Car car2 = car1; //reference the reference of car1, aka 69
car1.addFuel(20); //changes field of the reference 69
System.out.println(car2.getFuel()); //it will print 520 even tho we only changed it
on car1, this is because we actually changed 69 which both objects refer to.

call by value

The way that values are passed to methods in Java is called call-by-value:
For each parameter there is an expression, the expressions are evaluated, and the values
of the expressions are passed as actual values.
Thus, if a variable is passed to a method, the stored value of that variable in the calling
method won’t be changed.
Example code:

int n = 5;
do(n); //this wont change the value of 5
System.out.println(n);

int n = 5;
do(n + 10); //this will only add 10 to n in the method instance not the original n
instance
System.out.println(n);

static void do(int n) {


n = n + 10;
}
public static void doChange(int n) {
ClassName.n = n + 10; //this will change the value of n since we explicitly say
which n instance to change.
}

this means the value of 5 will stay 5 and wont be changed even after changing it in the
method since the value of the n in the method ends when the method call ends.
If reference variables are passed to a method, the stored values of the variables
(references to objects) won’t be changed.
But, we can use the references inside the method to change the instance fields of the
object.

BankAccount myAccount = new BankAccount(); //reference a segment in the memory as


myAccount
System.out.print(myAccount.getBalance()); // prints 0.0
changeObject(myAccount);
System.out.print(myAccount.getBalance()); // prints 0.05

static void changeObject(BankAccount b) { //b will reference the same memory


segment as whatever object the parameter is, here its myAccount
b.deposit(0.05); //this changes the segment myAccount points to not myAccount
itself and since b and myAccount reference the same point value will change
}

Naming:
it is just something we use to label our fields and methods to make accessing them easier
(you do not want to point at memory segments do you? its not fun)
generally, they start with lowercase and follow this style: helloWorld .

Initiating a field:
we follow this order: <access modifier> <data type> <name>
example: public int anything;

Initiating a method:
methods have 2 additional components ( parameters and method body ):
Parameters:
The inputs/variables the method intakes, you have to specify their data types.
Method body:
Contains the code that either returns the state or changes the state of a field (or anything
you code id to do maybe even launching nukes who knows)
We follow this order to initiate a method:
<access modifier> <data type to return> <method name> <parameter(s)> {method body}
example:

public void blaBlaBla(int a, String b, double P, boolean G){


/*
HERE WE CODE OUR METHODS FUNCTIONALITY
*/
}

Static and non-Static:


static or not is specified after specifying or not specifying the access modifier.

static non-static
it is a global variable shared by all objects It is declared without strings, but
belonging to a class (variable) each objects has its own assignment.
(variable)
can be called on the class or the object: can only be called on the object:
ClassName.fieldName (variable) or objectName.fieldName (variable) or
ClassName.methodName (Method) or objectName.methodName (Method).
objectName.fieldName (variable) or
objectName.methodName (Method)..

If you don’t explicitly set a value for a field, Java will assign a default value to it based on
its type. For example:
0 for int
0.0 for double
false for boolean
null for objects (like String )
some rules:
1. Instance and static fields can be used from non-static methods
2. Static fields can be used from static methods
3. Instance fields cannot be used by static method
4. Instance and static fields can be used by non-static methods
5. Static fields can be used by static methods
Encapsulation:
the first of the 4 principle of OOP (the idea that you do not need to know how something
works to use it.), it states that you don't need your fields to be public to be accessible, you
can make them private then create a method that accesses them (for security reasons):

//this is public, we cant just objectName.number it.


private int number;

//this returns the value of number publicly so insted you can


objectName.showNumber() it and store it in another variable to do what you want.
public int showNumber(){
return this.number;
}

encapsulation also makes it simpler to work with a programme, instead of making


someone do things manually, they can just call methods we code to do those tasks, for
example instead of everyone saying fuel +=5; fuel+=10 ...etc; we can make a method
that lets them just say what number they want to add: addFuel(int number)
Encapsulation has 2 main components (scoping and separation of implementation):
for scoping, we worry about what is private and what isn't
for implementation and interface, we hide how the code works by just providing a
method instead of the class, the user had to just call the method without worrying
about how the task is being done (implementation is the code they dont see, interface
are the method names they know to use).

Class Running:
Programmes can have muiltiple classes and multiple objects.
every runnable class has its own public static void main(String[] args)
In OOP there are 2 ways to build a programme, one where the main method is in the same
class and one where it is in a separate runnable class (separate is the mostly preferable
way).

Method Overloading (same name methods, different


parameters and operations):
when two methods have the same name they are said to be overloaded, for them to work
their parameters have to be different (in number of parameters or type of parameter).
This is common in constructors to be able to make different types of objects in the same
class.
Commenting Public Interface:
Remember how with encapsulation we aimed to simplify our code such that user does not
need to see our code to know how your programme works? well what if they want to know
how the code works?
Well, they read your documentatin (which you def wrote right?)
how do we write the documentation?
Well, java makes it easy by using javadoc commenting (javadoc is also the
programme that reads your comments and creates the documentation)
first: start the comment with /** and end it with */ .
second: for each method parameters, use @param tag followed by the parameter
name and description.
third: for each non-void method use @return tag followed by the parameter name
and description.

/**
* Creates a bank account
*@param initialBalance the starting balance in decimal format
*/
public BankAccount(double initialBalance){
balance = initialBalance
}

note that javadoc shows public/default methods in documentation you will have to do extra
steps for private ones (otherwise they wouldn't be private would they now?).

Class Import:
Java classes are grouped in packages. if you use a class from another package you must
import that class at the beginning of your programme:
les say you want to use class test.java in the package exams , you will have to
import using this format: import <packageName>.<className>
import exams.test
you can use * instead of test to import all classes in the exams package.
package = directory (folder)
class = file
class name has to match file name
package name has to match directory name
In Java, files and directories follow strict naming conventions to ensure the compiler and
runtime environment can locate classes and packages:
1. Class Naming and Files: Each public class in Java must be in a file with the same name
as the class. For instance, a class named Bob must be in a file named Bob.java . This is
required so Java can easily locate the definition of each class.
2. Package Naming and Directories: Packages in Java are essentially directory structures
that organize classes. For example, if you create a package named utils , Java expects
the classes in that package to be located in a directory named utils . Inside this directory,
you might have files like SomeUtility.java if the class name is SomeUtility .
3. The Classpath: The classpath is a crucial setting in Java that tells the compiler and
runtime where to look for classes and packages. By default, Java looks in the current
directory, but you can set the classpath to point to other directories or .jar files. This way,
Java knows where to find packages like utils even if they aren’t in the default location.

You can specify the classpath using the -classpath or -cp option when compiling or running
Java code. For example:

javac -cp .;path/to/directory MyProgram.java


java -cp .;path/to/directory MyProgram

Approach to Design and Implement Classes:


figure out what the system is and what our simulation needs to do, what classes does it
have and what should the classes do
your class should be CRUD-y, meaning they should have the Constructor, Reader,
Uptdater and Destructor methods:
- Creator/constructor: creates objects
- Reader: returns state of an object, no modifcation (assessor method)
- Updater: modify the state of field/object.
- Destructor: ends connection of an object to the data base
use appropriate names that make sense instead of a something , dont be vague (readers
= get Something , updaters = set Something )
document the public interface users are going to see so they know what to do.
determine instance variables
determine constructors
implement methods
Test your class

LECTURE2:

You might also like