Programming II Flashcards
What does new do?
new invokes Java’s mechanism for creating new objects.
new does four things:
- Reserves memory in the heap for the object
- Creates an object there using the class as a blueprint
- Runs a constructor method defined within the class
- Returns a reference to the object
How the user the Scanner

instance variables
variables inside a class but outside a method
constructors
- a special method that is used only to create an instance of a class
- initialise variables as soon as you create an object

3 characterstics of a class
- is a compile-time entity: created at development time, not at runtime
- is a blueprint from which objects are instantiated
- defines a collection of attributes (fields) and methods that all its instantiations will have
4 characterstics of an object
- is a run-time entity: it must be created from a class during program execution
- is an instance of a class
- stores a value for each field
- methods can be invoked on an object
identify each element of the following code:
int argsNum =
- “argsNum” is a variable
- “int” tells us the variable is of type int
- = assignment operator - takes whatever is on the right side and copies that value to the left side variable
encapsulation
The object maintains a boundary between its state and behaviour and the outside world.
Access modifiers enfore encapsulation:
- public - all classes have access to the element
- private - only methods inside the class have access
- protected - related to inheritance
- package - default, anyone from within package
difference between classes and objects and instances
A class is a blueprint which you use to create objects.
An object is an instance of a class - it’s a concrete ‘thing’ that you made using a specific class. So, ‘object’ and ‘instance’ are the same thing, but the word ‘instance’ indicates the relationship of an object to its class.
For example, suppose you have a class House. Your own house is an object and is an instance of class House. Your sister’s house is another object (another instance of class House).
how to create an object which is an instance of the class “House”
House myHouse = new House();
fields vs. attributes
An attribute is another term for a field. It’s typically a public constant or a public variable that can be accessed directly.
A class stores its state in fields.
A class aggregates attributes (fields) and methods (functions).
property
the getter and setter combination
fields vs. variables
Example of a inheritance use case
Suppose that you’re writing a human-resources application and want to use the Person class as the basis (also called the super class) for a new class called Employee. Being the child of Person, Employee would have all of the attributes of a Person class (Weight, Hair, Height), along with additional ones, such as:
- Taxpayer identification number
- Employee number
- Salary
import statements
An import statement tells the Java compiler where to find classes that you reference inside of your code.
import ClassNameToImport;
extra:
The class name should be fully qualified, meaning that it should include its package.
To import all classes within a package, you can put .* after the package name. For example, this statement imports every class in the com.makotojava package
import com.makotojava.*;
Importing an entire package can make your code less readable, however, so I recommend that you import only the classes that you need, using their fully qualified names.
How does a class declaration look like?
In general, class declarations can include these components, in order of when to write them:
- Modifiers such as public, private, and a number of others that you will encounter later.
- The class name, with the initial letter capitalized by convention.
- The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
- A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
- The class body, surrounded by braces, {}.

Classes can have two types of members…
variables and methods.
The values of a class’s variables distinguish each instance of that class and define its state. These values are often referred to as instance variables.
components of variables
A variable has:
- An accessSpecifier
- A dataType (primitive or other…)
- A variableName
- Optionally, an initialValue
The possible accessSpecifier values for variables are…
No specifier (also called friendly or package private access): Only objects whose classes are defined in the same package can see the variable.
private: Only the class containing the variable can see it.
public: Any object in any package can see the variable. (don’t ever use this value; see the public variables sidebar.)
protected: Any object defined in the same package, or a subclass (defined in any package), can see the variable.

two main categories of methods
- constructors
- all other methods, which come in many types
stack vs. heap
both reside on the memory
ADD MORE
nested if (else) statements

else if Statements

conditional operators
like using if else statments, but more compact:
- first part is the test: age > 50
- making it boolean using: ?
- if it’s true, execute first option
- seperate with :
- if it’s wrong, execute second option

for loop
cosists of three elements:
- where you want the loop to start
- where you want the loop to end (the condition)
- how much you want it to increment it by

do while loop
executes the body before checking the condition, hence guranteeing that the body is run at least once.

code a simple compound program

what loop do you usually use in arrays?
the (enhanced) for loop because it loops through every index of the array
(actually not sure if one or the other loop is prefered but yeah)
enhanced for loop
“int x” is the type and identifier
“bucky” what loop you want to use

how to create an array and how to access the value
int name[] = new int[10]
the 10 indicates how many values the array will store
access index 3: int[3]
OR
int name[] = {2,4,5,8}
an array is basically a single variable that can hold multiple values
arrays in methods
note that the change method is seperate from the main mehtod.
the change method uses the bucky array and adds 5 to each element

multidimensional arrays
first [] is for rows, second [] for columns

variable lengths variables
probably not needed for this course

this keyword
this is a reference variable that refers to the current object — the object whose method or constructor is being called.
You can refer to any member of the current object from within an instance method or a constructor by using this.
It can solve name clashes in constructors and other cases.

overloading constructors/methods
Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists.
The compiler does not consider return type when differentiating methods.

common visibilty setting for
- methods
- constructors
- fields
- most methods are public
- constructors are mostly public
- usually fields are private
how to create an object
Droid myDroid = new Droid();

2 types of variables
Variables contain either
- a reference to an object, or
- data of one of the primitive data types (double, int, char, boolean, etc.)


do primitive types have methods
Classes have methods and primitive types do not.
required elements of a method declaration
- modifiers (public, private)
- return type
- method name
- input parameters, preceded by their data types, enclosed by ()
- and a body between braces, {}
syntax of input parameters
input parameters names are preceded by their data types
public static double totalCost (int noOfUnits, double unitPrice){ return noOfUnits * unitPrice;
}
static
A static member is a member of a class that isn’t associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.
The two types of static members:
Static field:
private static int ballCount;
- The value of a static field is the same across all instances of the class. In other words, if a class has a static field named CompanyName, all objects created from the class will have the same value for CompanyName.
- Static fields are created and initialized when the class is first loaded. That happens when a static member of the class is referred to or when an instance of the class is created, whichever comes first.
Static method:
- Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.
- The best-known static method is main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.
- One of the basic rules of working with static methods is that you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields.
static methods
A method that can be called without creating some object first must be declared as static.
Static methods act on the whole class and are invoked with the class name (rather than a reference to an object instance of the class).
For example: Math.random();
static variables
Static variables are shared among all instances of a class. Unlike instance variables, they are not created and destroyed along with object instances of the class
typical use for a static variable
to keep track of the number of object instances that have been created
do or do not add static modifier to:
- class methods
- instance methods
- DO declare class methods as static
- DON’T declare instance methods as static
What do data declarations produce in every object of the class, and what is the exception?

code a getter method

code a setter method

what is null and a null pointer

do you understand this?

yes no maybe
how compare strings
to compare strings use equals(), never == or =!
String1.equals(String2)
example of an constructor in the class “Employee”

Hepler methods are usually (private or public)
private

does it make sense to have private constructors?
mostly no
Immutability
making variables FINAL so they and cannot cause trouble later on
Immutable objects provide protection
There is a special family of immutable objects called Value objects
- String (try modifying the contents of a String)• Integer – wrapper for int
- Double – wrapper for double
- etc.
Value objects (deliberately) look and feel a bit like primitive values – but they are still objects!
Checklist when writing Classes
- Defining classes, fields and methods
- Constructors
- Packages
- Encapsulation
- Visibility: public, private, package
- Class, field and method visibility
though this is only the basics…
What problem is packages solving?
The Problem:
- The standard Java class library contains 2500+ classes!
- There are thousands of open source projects, each providing hundreds more classes
- We need a mechanism for organising them!
What are packages?
groups together families of Java classes
A package may contain other packages: hierarchical naming
- java.util.Random
- java.lang – contains class String and others
- tutorial1.collatz – contains solutions to question 1 of tutorial sheet 1
How to find the standard library?
The standard library is already on the classpath.
how to delcare a package
package examples.games;
Extra
- Compile code within a package by including its root directory in classpath
- Imported packages must also be included in the classpath