Documente Academic
Documente Profesional
Documente Cultură
Objectives:
Discuss primitive data types Learn how to declare fields and local variables Learn about arithmetic operators, compound assignment operators, and increment / decrement operators Discuss common mistakes in arithmetic
Variables
A variable is a named container that holds a value. q = 100 - q; means:
1. Read the current value of q 2. Subtract it from 100 3. Move the result back into q
5 count
Variables (contd)
Variables can be of different data types: int, char, double, boolean, etc. Variables can hold objects; then the type is the class of the object. The programmer gives names to variables. Names of variables usually start with a lowercase letter.
Variables (contd)
A variable must be declared before it can be used:
int count;
double
Type JButton Walker
x, y;
go; amy;
Name(s)
String firstName;
Variables (contd)
The assignment operator = sets the variables value:
count = 5; x = 0; go = new JButton("Go"); firstName = args[0];
Variables (contd)
A variable can be initialized in its declaration:
int count = 5; JButton go = new JButton("Go"); String firstName = args[0];
Variables: Scope
Each variable has a scope the area in the source code where it is visible. If you use a variable outside its scope, the compiler reports a syntax error. Variables can have the same name when their scopes do not overlap.
Fields
Fields are declared outside all constructors and methods. Fields are usually grouped together, either at the top or at the bottom of the class. The scope of a field is the whole class.
Fields (contd)
Scope
public class SomeClass { Fields } Constructors and methods
Or:
public class SomeClass { Constructors and methods Fields
Scope
Local Variables
Local variables are declared inside a constructor or a method. Local variables lose their values and are destroyed once the constructor or the method is exited. The scope of a local variable is from its declaration down to the closing brace of the block in which it is declared.
Scope
}
} ... }
Variables (contd)
Use local variables whenever appropriate; never use fields where local variables should be used. Give prominent names to fields, so that they are different from local variables. Use the same name for local variables that are used in similar ways in different methods (for example, x, y for coordinates, count for a counter, i, k for indices, etc.).
Variables (contd)
Common mistakes:
public void someMethod (...) { int x = 0; ... int x = 5; // should be: x = 5; ...
Variable declared twice within the same scope syntax error
Variables (contd)
Common mistakes:
private double radius; ... public Circle (...) // constructor { double radius = 5; ...
Declares a local variable radius; the value of the field radius remains 0.0
Strings
String is not a primitive data type Strings work like any other objects, with two exceptions:
Strings in double quotes are recognized as literal constants + and += concatenate strings (or a string and a number or an object, which is converted into a string) "Catch " + 22 "Catch 22"
f.toString() is called
automatically
Public: Public declared items can be accessed everywhere. Protected: Protected limits access to inherited and parent classes (and to the class that defines the item). Private: Private limits visibility only to the class that defines the item. Static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Final: Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. Transient: A transient variable is a variable that may not be serialized. Volatile: a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.
CLASSES
Introduction
Java is a true OO language and therefore the underlying structure of all Java programs is classes. Anything we wish to represent in Java must be encapsulated in a class that defines the state and behaviour of the basic program components known as objects. Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them. A class essentially serves as a template for an object and behaves like a basic data type int. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism.
Classes
A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
Circle
centre radius
circumference() area()
Classes
A class is a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition:
class ClassName [extends SuperClassName] { [fields declaration] [methods declaration]
Bare bone class no fields, no methods public class Circle { // my circle class }
Adding Methods
A class with only data fields has no life. Objects created by such a class cannot respond to any messages. Methods are declared inside the body of the class but immediately after the declaration of data fields. The general form of a method declaration is:
type MethodName (parameter-list) { Method-body; }
Data Abstraction
Declare the Circle class, have created a new data type Data Abstraction Can define variables (objects) of that type:
Circle aCircle; Circle bCircle;
null
null
bCircle = aCircle;
Before Assignment
aCircle bCircle
Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0
Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area();
Class
A blueprint for objects of a particular type Defines the structure (number, types) of the attributes Defines available behaviors of its objects
Object
Attributes
Behaviors
Class: Car
Object: a car
Behaviors: Behaviors: Add/remove a passenger Get the tank filled Report when out of gas
Class
A piece of the programs source code Written by a programmer
vs.
Object
An entity in a running program Created when the program is running (by the main method or a constructor or another method)
Class
Specifies the structure (the number and types) of its objects attributes the same for all of its objects Specifies the possible behaviors of its objects
vs.
Object
Holds specific values of attributes; these values can change while the program is running
Libraries
Java programs are usually not written from scratch. There are hundreds of library classes for all occasions. Library classes are organized into packages. For example:
java.util miscellaneous utility classes java.awt windowing and graphics toolkit javax.swing GUI development package
import
Full library class names include the package name. For example:
java.awt.Color javax.swing.JButton
import statements at the top of the source file let you refer to library classes by their Fully-qualified short names: name
import javax.swing.JButton; ... JButton go = new JButton("Go");
import (contd)
You can import names for all the classes in a package by using a wildcard .*:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
Imports all classes from awt, awt.event, and swing packages
java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes.
SomeClass.java
import ...
import statements
Fields
Attributes / variables that define the objects state; can hold numbers, characters, strings, other objects Procedures for constructing a new object of this class and initializing its fields Actions that an object of this class can take (behaviors)
Constructors
Methods
Fields
Constructor
public void moveForward (int distance) { coordinates.shift (distance, 0); } public void moveSideways (int distance) { coordinates.shift (0, distance); } ...
}
Methods
Constructors
Short procedures for creating objects of a class Always have the same name as the class Initialize the objects fields May take parameters A class may have several constructors that differ in the number and/or types of their parameters
Constructors (contd)
public class Foot { private Image picture; private CoordinateSystem coordinates;
The name of a constructor is always the same as the name of the class
public Foot (int x, int y, Image pic) { A constructor can take parameters picture = pic; coordinates = new CoordinateSystem(x, y, pic); } ... }
Initializes fields
Constructors (contd)
// FootTest.java ... An object is created with Image leftShoe = ...; the new operator ... Foot leftFoot = new Foot (5, 20, leftShoe); ...
...
public Foot (int x, int y, Image pic) { ... } ... }
Constructors (contd)
Methods
Call them for a particular object:
leftFoot.moveForward(20);
amy.nextStep( ); ben.nextStep( );
go.setText("Stop");
Methods (contd)
The number and types of parameters (a.k.a. arguments) passed to a method must match methods parameters:
public void drawString ( String msg, int x, int y ) { ... } g.drawString ("Welcome", 120, 50);
Methods (contd)
A method can return a value to the caller The keyword void in the methods header indicates that the method does not return any value
public void moveSideways(int distance) { ... }
Methods (contd)
Constructors and methods can call other public and private methods of the same class. Constructors and methods can call only public methods of another class.
private method