Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
// TestGreeting.java
// Sample "Hello World" Application
public class TestGreeting{
public static void main(String[] args) {
Greeting hello = new Greeting("Hello");
hello.greet("World");
}
}
A Basic Java Application-Contd..
//Greeting.java
public class Greeting{
private String salutation;
Greeting(String s){
salutation = s;
}
public void greet(String whom){
System.out.println(salutation+” “+whom);
}
}
Compiling and Running
Compiling TestGreeting.java
javac TestGreeting.java
Greeting.java is compiled automatically
Running an application
Java TestGeeting
The Java Virtual Machine
TestGreeting.class Greeting.class
java JVM
Runtime
Class Loader
Hardware
Java Runtime Environment
Ensures that
The code adheres to the JVM specification
The code does not violate system integrity
The code causes no operand stack overflows or
underflows
The parameter types for al operational code are
correct
No illegal data conversions have occurred
Object Oriented Programming
Objectives
Example
public class Vehicle{
private double maxLoad;
public void setMaxLoad(double val)
{
maxLoad=val;
}
}
Declaring Attributes
Example
public class Foo{
public int x;
private float y = 1000.0F;
private String name=“Fred
Smith”;
}
Declaring Methods
Examples
public class Thing{
private int x;
public int getX(){
return x;
}
public void setX(int new_x){
x=new_x;
}
}
Accessing Object Members
The Problem
MyDate Client code has direct access to
internal data
+day : int
MyDate d = new MyDate();
+month : int
+year : int d.day=32; //invalid day
d.month=2;d.day=30;//wrong
d.day=d.day+1; //no check
Information Hiding
The Solution:
MyDate Client code must use setters /
-day: int getters to create internal data
-month: int MyDate d = new MyDate();
-year: int d.setDay(32);
+getDay(): int //invalid returns false
+getMonth(): int
d.setMonth(2);d.setDay(30);
+getYear(): int
//setDay returns false
+setDay(d: int): boolean
+setMonth(m: int) d.setDay(d.getDay()+1);
+setYear(y: int) //will return false if wrap
occurs
-validDay(d: int): boolean
Encapsulation
Example
public class Thing{
private int x;
public Thing(){
x=47;
}
public Thing(int new_x){
x=new_x;
}
}
The Default Constructor
Example
package shipping.reports.web;
import shipping.domain.*;
import java.util.List;
import java.io.*;
public class VehicleCapacityRepport{
private List vehicles;
public void generateReport(Writer op){
---
}
}
Packages
domain
GUI
Company Vehicle
Truck RiverBarge
reports
The package Statement
Example
package shipping.reports.web;
Specify the package declaration at the beginning of
the source file
Only one package declaration per source file
If no package declaration is declared, the class
belongs to the default package
Package names must be hierarchical and separated
by dots
The import Statement
shipping/
domain/
Company.class
Vehicle.class
RiverBarge.class
Truck.class
GUI/
reports/
VehicleCapacityReport.class
Terminology Recap