Title: Variables and Types 4.2
1Variables and Types (4.2)
- Declarations
- Primitive type variables
- Reference type variables
- Arrays
- Type conversion and compatibility
2What is a Variable
- A location in computer memory for holding data
- Type of data is more or less specified
- Data may be a reference to other data rather than
the data itself
3Declaration
- A declaration associates a name with a variable
and requests that the variable be allocated space
in memory - Type of the variable
- Primitive
- Reference to object or array
- lttypegt ltidentifiergt
4Primitive Type Variables
- In declaring a primitive type variable, the type
is one of the primitive types - The variable, in this case, holds that type of
data - Initialization is to 0 or false, if automatic
initialization is provided
5Reference Types
- A class
- An array
- An interface (similar to an abstract class)
6Anonymous Objects
- Objects are allocated that do not have names
directly attached - These objects are accessed via references
- There may be multiple references to the same
object, allowing sharing
7Garbage Collection
- Automatically destroys an object when there is no
reference to it - To garbage collect and object, assign null to
the object reference - Person per_obj
- per_obj new Person(Jose)
-
- per_obj null
8Equality of Reference
- Testing that two object references are equal
- if (ref1 ref2)
- . . .
- Testing that two objects are equal
- if ( ref1.equals(ref2))
- . . .
9Type conversion and compatibility
- There are two main types of compatibility
- Widening and narrowing of numeric types
- Substitutability
10Widening and Narrowing
- Generally, numeric values can be converted to
another numeric type - From smaller to larger is automatic
- Byte, short, int, long, float, double
- From larger to smaller requires an explicit cast,
for type conversion - (float)2.3
- (int) 2.3
11Conversion of Reference Types (4.2.2)
- The widening is always allowed and is carried out
implicitly - Person y
- // class Male is a subclass of Person
- Male x new Male()
- . . .
- y x
-
12Narrowing of Reference Types
- Requires explicit casts, also known as
downcasting - The object being referenced is not affected
- x (Male) y // downcasting
13Arrays
- A static data structure
- In Java, and array variable is an object
reference to the actual data structure - Memory is allocated to hold n elements of the
same type
14Declaraing and Creating Arrays
- int myarray new int 100
- Person parray new Person25
- // each element in the array is an
- // object reference
- String name John Smith
- parrayi new Person(name)
15Statements
- Expression
- Blocks
- Local variable declarations
- Return
- Structured
- Null statement
16Expression Statements
- Any expression can be used as a statement by
following it with a semicolon - Some are not very helpful
- 23
- Generally useful with some side effect
- x 3
17Blocks
- In a number of places, Java requires a single
statement. A block of statements counts as a
single statement in that context. - A block sets up a local context for defining
variables. - Open and closed curly braces.
18Scope of a Definition of a Name
- The scope of a definition of a name is that part
of the program that can refer to that name and
access the defined entity through it. - Scope is usually bounded by curly braces
- Public scope is the entire program
19Local Variable Declarations
- Local variable declarations have a scope bounded
by the smallest block containing them. - The variable ceases to exist at the close of the
scope. - Note, the reference may be gone, but not the
object - Local variables must be initialized
20Structured
- Sequence
- Statements are placed one after the other to
indicate sequence - Choice, selection, alternation
- Repetition
21Choice
- if for two-way choice
- Optional else
- Use blocks for multiple statements in either part
- switch for multi-way choice
- Ill not use them
22Repetition
- Pre-test while
- Counting for
- Post-test do while
- I wont use this
23Pre-test Loop
- while( ltconditiongt )
- ltstatementgt
- Continues as long as ltconditiongt is true
- Sometimes requires awkward logic while not done
24Counting Loop
- for( int i 0 i lt N i )
- ltstatementgt
- Statement is executed for each value of i from 0
to N-1 - Mixes with arrays very well
- sum.java (p. 97)
25Breaking Out
- The break statement forces early termination of
one or more levels of loops - Loops can be labeled to help specify which loop
is being exited - Ill avoid using break and continue
26Searching Through a List
- Array of strings, data
- A key value to search for
- int i 0
- while( i lt data.length key ! datai )
- i
27Class Declarations
- ltmodifiersgt class ltnamegt
- extends ltsupernamegt
- implements ltinterfacegt, ltinterfacegt
-
- ltmember declarationsgt
28Modifiers for a Class
- Access
- public
- ltnonegt
- abstract
- final
29Modifiers for Members
- ltnonegt
- public
- protected
- private
- static
- final
30Modifiers for Methods
- abstract
- synchronized
- native
31Modifiers for Fields
32Accessibility
- Table on page 103
- Generally, fields will be private
- Generally, methods will be public
33Constructors
- Constructors initialize the fields of a class
- Sometimes they must reference constructors of
classes they extend - Overloading of constructors
34Accessing Fields and Methods
- Members
- objectName.fieldName
- objectName.methodName(.)
- Static members
- className.fieldName
- className.methodName()
35Declaration Example
public class Point public int x, y
public void move(int dx, int dy) x dx
y dy // end class Point Point
point1 // Point not created Point point2 new
Point() // x, y default initial
values point1 point2 point1 null
36Explicit Initializer
public class Point public int x 0, y 0
// public void move(int dx, int dy)
x dx y dy // end class
Point Point point1 new Point() // (0,0)
37Constructor
- Constructors are used to initializes data in the
class. - public class Coin
- public Coin (double aValue, String aName)
Constructor - value aValue
- name aName
-
- public Coin( ) Default Constructor
- value 0
- name Dollar
-
- private double value
- private String name
-
38Constructors
- public class Point
- public int x, y
- public Point() // no-arg
- x 0 y 0
-
- public Point(int x0, int y0)
- x x0 y y0
-
- // end class Point
- Point point1 new Point() // no-arg
- Point point2 new Point(20, 20)
39Using Constructors
- Constructors are invoked after default initial
values are assigned. - No-arg constructor is provided as a default when
no other constructors are provided
40Object Reference this
- You can use this inside a method
- It refers to the current object on which the
method is invoked. - It's commonly used to pass the object itself as a
parameter - aList.insert(this)
41This
- It can also be used to access hidden variables
- public class Point
- public int x, y
- public Point(int x, int y)
- this.x x this.y y
-
-
42Static Variables
- Static variable or fields are shared by all
objects of the class, rather than one value per
object. - Static variables are also known as class
variables. - Non-static variables are also known as instance
variables.
43Example of Static Variable
- class IDCard
- public long id
- protected static long nextID 0
- public IDCard()
- id nextID
-
- // end class IDCard
44Static Methods
A static method can only access static variables
and invoke other static methods can not use this
reference. class IDCard public long id
protected static long nextID 0 ...
public static void skipID() nextID
45Invoking Methods
- Non-static methods must be invoked through an
object reference - object_reference.method(parameters)
- Static methods can be invoked through an object
reference or the class name - class_name.method(parameters)
46Invoking Methods
- So, you can do either of the following
- IDCard.skipID() // the preferred way
- IDCard mycard new IDCard()
- mycard.skipID()
47final Variables
Final variables are named constants. class
CircleStuff static final double
pi3.1416 . . . Final variables
are also static.
48final Variables
Final variables are named constants. class
CircleStuff static final double
pi3.1416 . . . Final variables
are also static.
49Overloading
- Each method has a signature its name together
with the number and types of its parameters - Methods Signatures
- String toString() ()
- void move(int dx,int dy) (int,int)
- void paint(Graphicsg) (Graphics)
- Two methods can have the same name if they have
different signatures. They are overloaded.
50Overloading Example
- public class Point
- protected double x, y
- public Point() // default constructor
- x 0.0 y 0.0
-
- public Point(double x, double y)
- this.x x this.y y
-
- // The two constructors are overloaded
- . . .
51Class Point Continued
- /calculate the distance between this point and
the other point / - public double distance(Point other)
- double dx this.x - other.x
- double dy this.y - other.y
- return Math.sqrt(dx dx dy dy)
-
52Class Point continued
- /calculate the distance between this point
and (x,y)/ - public double distance(double x, double y)
- double dx this.x - x
- double dy this.y - y
- return Math.sqrt(dx dx dy dy)
-
- /calculate the distance between this point
and the origin/ - public double distance()
- return Math.sqrt(x x y y)
-
- // other methods
- // end class Point
53Parameter Passing
- Parameters are passed by value
- We will develop an example, using Rectangle, that
shows how this works out in practice.
54Accessor
- Accessor methods return information about an
object without changing the data. - Some classes are design to be immutable meaning
all methods only access the data never changing
it. - public double getBalance( )
- return balance
-
55Mutator
- Mutators change the state of an object.
- Java recommens that mutators have the return type
of void to prevent it from acting like an
accessor. - public void deposit (double amount)
- balance balance amount
-
56Method Parameters
- Two types of parameters
- Implicit - The object on which a method is
invoked. - Explicit - Parameter of a method other than the
object. - Example,
- CheckingAccount.deposit(amount)
-
- Implicit Explicit
57Passing Objects to Methods
- Parameters in a Java method are passed by value
- This means that a copy of the actual parameter
(the value passed in) is stored into the formal
parameter (in the method header) - Passing parameters is essentially an assignment
- When an object is passed to a method, the actual
parameter and the formal parameter become aliases
of each other
58Passing Objects to Methods
- What you do to a parameter inside a method may or
may not have a permanent effect (outside the
method) - See ParameterPassing.java (page 226)
- See ParameterTester.java (page 228)
- See Num.java (page 230)
- Note the difference between changing the
reference and changing the object that the
reference points to
59Static Methods
- A static methods is used when an implicit
parameter is not needed. - The keyword static, must be included in the
methods heading. - public static boolean approxEqual(double x,
double y) - . . .
-
60Static Variables
- Static variable are called class variables
because a single value is needed for the entire
class. - Every method in the class can access the static
variable. - public BankAccount ( )
- lastAssignedNumber
- accountNumber lastAssignedNumber
61Sequence of Comparison
- Certain situation require if/else testing in the
correct order. - Example,
62Nested Branches
- Nested branches allow multiple tests asked which
will result many different outcomes. - A tax program will do this with two cases,
married and single. The remaining question will
be nested under the main decisions.
63Loops
- while, for, and do while statements implements
repetition. - Example,
- while (true)
- body
-
- Loops are useful for operations that take more
that one execution of a piece of code.
64Examples
- While loops Do loops
- i start do
- while (i lt end) . . .
- . . . while (i lt end)
- i
-
- For loops
- for (I start I lt end i)
- . . .
-
65Processing Input
- To be able to process a set of numbers, a line at
a time, it is possible to use a loop. - Simple read in data until the end is reached.
- boolean done false
- while ( ! done)
- String line console.readLine()
- if(line null)
- done true
- else
- . . .
-
-
66Classes
- Classes are formed by attributes and methods.
- Attributes can be any that describes the object
like color, length, and font. - Methods act on the attributes in someway.
- There are three types constructors, accessors,
and mutators.
67Inheritance
- This is a used when a new class is to inherit
features of the old class. - Doing this allows the programmer reuse code that
has already been tested. - Superclass is a more general class when a
subclass is a more specific class.
68Inheritance Form
- public class SavingsAccount extends BankAccount
- public SavingsAccount (double rate)
Used to show inheritance - interestRate rate
-
- public void addInterest ()
Added features - double interest getBalance ()
interestRate / 100 - deposit (interest)
-
- private double interestRate
69Inheritance and Extended Classes
- Extended classes are also known as subclasses.
- Inheritance models the is-a relationship.
- If class E is an extended class of class B, then
any object of E can act-as an object of B. - Only single inheritance is allowed among classes.
- All public and protected members of a super class
are accessible in the extended classes. - All protected members are also accessible within
the package.
70Constructors of Extended Classes
- The constructor of the super class can be
invoked. - super(...) must be the first statement.
- If the super constructor is not invoked
explicitly, by default the no-arg super() is
invoked implicitly. - You can also invoke another constructor of the
same class.
71Example
- public class ColoredPoint extends Point
- public Color color
- public ColoredPoint(double x, double y, Color
color) - super(x, y)
- this.color color
-
- public ColoredPoint(double x, double y)
- this(x, y, Color.black) // default value of
color -
- public ColoredPoint()
- color Color.black
-
- // end class ColoredPoint
72Example2
- Default no-arg constructor is provided
- public class Extended extends Super
- public Extended()
- super()
-
- // methods and fields
-
73Interfaces
- They are use to allow multiple inheritance since
Java forbids full inheritance. - Interfaces are similar to classes but several
restrictions, - Does not have instance variables.
- All methods are abstract, meaning they have name,
parameters, and return type but they dont have
implementations. - All interfaces are automatically public.
74The Implicit Argument
- Within the method of a class, you may refer to
fields and methods of that class by name, without
the object reference - If the current object needs to be referenced, it
can be referenced as this - Why wont the name in the main program work?
75Interfaces
- A Java interface is a collection of abstract
methods and constants - An abstract method is a method header without a
method body - An abstract method can be declared using the
modifier abstract, but because all methods in an
interface are abstract, it is usually left off - An interface is used to formally define a set of
methods that a class will implement
76Interfaces
public interface Doable public void
doThis() public int doThat() public void
doThis2 (float value, char ch) public boolean
doTheOther (int num)
77Interfaces
- An interface cannot be instantiated
- Methods in an interface have public visibility by
default - A class formally implements an interface by
- stating so in the class header
- providing implementations for each abstract
method in the interface - If a class asserts that it implements an
interface, it must define all methods in the
interface or the compiler will produce errors.
78Interfaces
public class CanDo implements Doable public
void doThis () // whatever
public void doThat () // whatever
// etc.
79Interfaces
- A class that implements an interface can
implement other methods as well - A class can implement multiple interfaces
- The interfaces are listed in the implements
clause, separated by commas - The class must implement all methods in all
interfaces listed in the header
80Arrays
- An array is a collection of data items of same
type. - In java we define arrays as follows
- double data new double 10
- This is the definition of a variable data whose
type is double . That is, data is a reference
to an array of floating-point numbers. The call
new double 10 creates the actual array of 10
numbers. - When an array is first created, all values are
initialized with 0, false or null. - To get some value into the array we must specify
which slot in the array you want to use. - Slots in java are numbered starting at 0.
-
81Array
- A java array has an instance variable length,
which you can access to find the size of the
array. - for ( int i 0 i lt data.length i )
- note that there are no parentheses after
length - We can copy array variables because they hold
references to the actual array. We can also use - System.arraycopy(from, fromStart, to,
toStart, count) - System.arraycopy(data, 0, newData, 0,
data.length)
82Vectors
- Vector is a container of objects that grows
dynamically. You add new elements using the add
method. - Vectors are objects of a class and not an array,
thus you cannot use the operator to access a
particular slot in the vector. - Instead we use the set method to write an element
and get method to read an element. - Vector product new Vector()
- Product toaster .
- product.set(0 , toaster)
- This stores object toaster in position 0.
- We use the size method to get the size of the
vector. As with arrays, vector positions start at
0.
83Vectors
- Since vectors only hold objects we cannot have a
vector of pure number such as integers, floating
point. - To store numbers in a vector we must use a
wrapper class such as Integer, Double. - We must cast and call the doubleValue method to
get the original floating point number. - Unlike C, element access in Vectors seems to be
more complicated then in Arrays.