Show Menu
Cheatography

COMP 250 MIDTERM Cheat Sheet (DRAFT) by

A cheatsheet for COMP 250, Algorithms and data structures

This is a draft cheat sheet. It is a work in progress and is not finished yet.

using a package member from outside its package

must use fully qualified name to use class (member)
animal­s.Dog myDog = new animal­s.D­og();
this is from the animals package

how to prevent

create a deep copy in the constr­uctor

condition for class to be immutable

if all fields are private and no mutator methods
only wao to assign values to fields through constr­uctor
if public or set type is provided, its mutable
if fields are private and no get or set method­s...its immutable

static vs non-static

static is called on class
from outside class: ClassN­ame.me­tho­dName()
nonstatic is called on specific object
call from outside class: obj.me­tho­dName()
reference static from outside class
ClassN­ame.va­rName
reference obj from outside class
obj.va­rName

changing static

g2.msg, g.msg
change g2.msg if static will change g.msg
 

java auto imports two packages for each src file

java.lang package
the current package

try this!

in patient class, overload the constr­uctor by adding another one that takes as input age, name, temper­atures of new patient
does it make a difference if we copy the elements of the input array, or just the address directly

this field in static method

no

if field is package private, (no access modifier)

can access as long as classes are in the same package
public class Dog { String name';}
 
from class beagle, can access through d.name
 

overlo­ading constr­uctor

create two constr­uctors in same class file
one takes no input, other takes input

does a constr­uctor have to initialize all fields?

no...other fields will be initia­lized by default
in java you cannot assign default value in args

static method access

if method is static, has access to class variables
if method is not static, has access to both class and instance variables

can only access field by class name if

public and static, not public is insuff­icient

the result of the new operator is

a reference to the new object
Random random­Gen­erator = new Random();
 

methods; same package but different classes

we need to use name of class.m­ethod to access

can we access private field from constr­uctor?

january 19 second slide
no cannot, need getter or setter...but the field is initia­lized just not accesible

in what case do we try to leave fields public?

if they are constants

private vs public fields

private field is accessible only within class in which it was written
public field is accessible from anywhere
package private is only accessible within class, or its own packag­e...not accessible to world