Sunteți pe pagina 1din 54

Data Types

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

mov ax,q mov bx,100 sub bx,ax mov q,bx

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.

{ int k = ...; ... } for (int k = ...) { ... }

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.

Local Variables (contd)


public class SomeClass { ... public SomeType SomeMethod (...) {
Local variable declared

Scope

Local variable declared

}
} ... }

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

Primitive Data Types


int double char boolean byte short long float

Used in Java Methods

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"

From Objects to Strings


The toString method is called:
public class Fraction { private int num, denom; ... public String toString () { return num + "/" + denom; } } Fraction f = new Fraction (2, 3); System.out. println (f) ; Output: 2/3

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 Fields: Class Circle with fields


Add fields
public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }

The fields (data) are also called the instance varaibles.

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; }

Adding Methods to Class Circle


public class Circle {

public double x, y; // centre of the circle public double r; // radius of circle


//Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { Method Body return 3.14 * r * r; } }

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;

Class of Circle cont.


aCircle, bCircle simply refers to a Circle object, not an object itself.
aCircle bCircle

null

null

Points to nothing (Null Reference)

Points to nothing (Null Reference)

Creating objects of a class


Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects
aCircle = new Circle() ; bCircle = new Circle() ;

Creating objects of a class


aCircle = new Circle(); bCircle = new Circle() ;

bCircle = aCircle;

Creating objects of a class


aCircle = new Circle(); bCircle = new Circle() ;

bCircle = aCircle; Before Assignment


aCircle bCircle

Before Assignment
aCircle bCircle

Accessing Object/Circle Data


Similar to C syntax for accessing data defined in a structure.
ObjectName.VariableName ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0

Executing Methods in Object/Circle


Using Object Methods:
sent message to aCircle

Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area();

Using Circle Class


// Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } } [raj@mundroo]%: java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002

Classes and Objects


A class is a piece of the programs source code that describes a particular type of objects. OO programmers write class definitions. An object is called an instance of a class. A program can create and use more than one object (instance) of the same class.

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

Attributes: String model Color color int numPassengers double amountOfGas

Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5

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

Behaves appropriately when

Classes and Source Files


Each class is stored in a separate file The name of the file must be the same as the name of the class, with the extension .java Car.java By convention, the
public class Car { ... } name of a class (and its source file) always starts with a capital letter.

(In Java, all names are case-sensitive.)

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

public class SomeClass header Class


{

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

public class Foot


{ private Image picture; private CoordinateSystem coordinates; public Foot (int x, int y, Image pic) { picture = pic; coordinates = new CoordinateSystem (x, y, pic); }

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 class Foot {

...
public Foot (int x, int y, Image pic) { ... } ... }

The number, order, and types of parameters must match Constructor

Constructors (contd)

JButton go = new JButton("Go");

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) { ... }

Encapsulation and Information Hiding


A class interacts with other classes only through constructors and public methods Other classes do not need to know the mechanics (implementation details) of a class to use it effectively Encapsulation facilitates team work and program maintenance (making changes to the code)

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.

Class X private field public method

Class Y public method

private method

S-ar putea să vă placă și