Você está na página 1de 19

public class mainclass {

public static void main(string[] args) {


system.out.println("java");
}
}

public class mainclass


{
public static void main( string args[] )
{
scope testscope = new scope();
testscope.begin();
}
}
class scope
{
private int x = 1;

public void begin()


{
int x = 5; // method's local variable x shadows field x

system.out.printf( "local x in method begin is %d\n", x );

uselocalvariable();
usefield();
uselocalvariable();
usefield();

system.out.printf( "\nlocal x in method begin is %d\n", x );


}

public void uselocalvariable()


{
int x = 25; // initialized each time uselocalvariable is called

system.out.printf("\nlocal x on entering method uselocalvariable is %d\n", x );


++x; // modifies this method's local variable x
system.out.printf(
"local x before exiting method uselocalvariable is %d\n", x );
}

// modify class scope's field x during each call


public void usefield()
{
system.out.printf("\nfield x on entering method usefield is %d\n", x );
x *= 10; // modifies class scope's field x
system.out.printf("field x before exiting method usefield is %d\n", x );
}
}
local x in method begin is 5

local x on entering method uselocalvariable is 25


local x before exiting method uselocalvariable is 26

field x on entering method usefield is 1


field x before exiting method usefield is 10

local x on entering method uselocalvariable is 25


local x before exiting method uselocalvariable is 26

field x on entering method usefield is 10


field x before exiting method usefield is 100

local x in method begin is 5

///multiple constructors....
class sphere {
int radius = 0;

sphere() {
radius = 1;
}

sphere(int radius) {
this.radius = radius;
}
}

5.3.2 passing objects to a method

class sphere {
double radius; // radius of a sphere

sphere() {

// class constructor
sphere(double theradius) {
radius = theradius; // set the radius

public class mainclass {


public static void main(string[] arg){
sphere sp = new sphere();

amethod(sp);
}

private static void amethod(sphere sp){


system.out.println(sp);
}
}

5.1.9 class with a constructor to initialize instance variables

public class mainclass


{
public static void main( string args[] )
{
account account1 = new account( 50.00 ); // create account object
account account2 = new account( -7.53 ); // create account object

system.out.printf( "account1 balance: $%.2f\n", account1.getbalance() );


system.out.printf( "account2 balance: $%.2f\n\n", account2.getbalance() );

double depositamount; // deposit amount read from user

depositamount = 10.10;
account1.credit( depositamount ); // add to account1 balance

system.out.printf( "account1 balance: $%.2f\n", account1.getbalance() );


system.out.printf( "account2 balance: $%.2f\n\n", account2.getbalance() );

depositamount = 12.12;
account2.credit( depositamount ); // add to account2 balance

system.out.printf( "account1 balance: $%.2f\n", account1.getbalance() );


system.out.printf( "account2 balance: $%.2f\n", account2.getbalance() );
}

class account
{
private double balance; // instance variable that stores the balance

// constructor
public account( double initialbalance )
{
if ( initialbalance > 0.0 )
balance = initialbalance;
}

public void credit( double amount )


{
balance = balance + amount;
}

public double getbalance()


{
return balance;
}

account1 balance: $50.00


account2 balance: $0.00

account1 balance: $60.10


account2 balance: $0.00

account1 balance: $60.10


account2 balance: $12.12

5.4.2 dynamically changing the behavior of an object via composition (the 'state' design pattern)

abstract class actor {


public abstract void act();
}

class happyactor extends actor {


public void act() {
system.out.println("happyactor");
}
}

class sadactor extends actor {


public void act() {
system.out.println("sadactor");
}
}

class stage {
private actor actor = new happyactor();

public void change() {


actor = new sadactor();
}

public void performplay() {


actor.act();
}
}

public class mainclass {


public static void main(string[] args) {
stage stage = new stage();
stage.performplay();
stage.change();
stage.performplay();
}
}

happyactor
sadactor

5.8.4 recursive factorial method

public class mainclass {


public static void main(string args[]) {
for (int counter = 0; counter <= 10; counter++)
system.out.printf("%d! = %d\n", counter, factorial(counter));

// recursive declaration of method factorial


public static long factorial(long number) {
if (number <= 1) // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
else
// recursion step
return number * factorial(number - 1);
}
}

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

5.5.6 demonstration of both constructor and ordinary method overloading

class myclass {
int height;

myclass() {
system.out.println("planting a seedling");
height = 0;
}

myclass(int i) {
system.out.println("creating new tree that is " + i + " feet tall");
height = i;
}

void info() {
system.out.println("tree is " + height + " feet tall");
}

void info(string s) {
system.out.println(s + ": tree is " + height + " feet tall");
}
}

public class mainclass {


public static void main(string[] args) {
myclass t = new myclass(0);
t.info();
t.info("overloaded method");
// overloaded constructor:
new myclass();
}
}

creating new tree that is 0 feet tall


tree is 0 feet tall
overloaded method: tree is 0 feet tall
planting a seedling
5.5.3 pass long parameters to overloading method

it is legal to have these two methods in the same class.

public class mainclass {


public int printnumber(int i) {
return i*2;
}

public long printnumber(long i) {


return i*3;
}
public static void main(string[] args) {

printnumber(3) will invoke this method:


public int printnumber(int i)

to call the second, pass a long:


printnumber(3l)

5.12.18 local inner class can have a constructor

interface counter {
int next();
}

public class mainclass{

private int count = 0;


counter getcounter(final string name) {
// a local inner class:
class localcounter implements counter {
public localcounter() {
// local inner class can have a constructor
system.out.println("localcounter()");
}
public int next() {
system.out.print(name); // access local final
return count++;
}
}
return new localcounter();
}

public static void main(string[] args) {


mainclass lic = new mainclass();
counter c1 = lic.getcounter("local inner ");
}
}

5.12.7 nesting a class within a method

public class mainclass {


public a dest(string s) {
class b implements a {
private string label;

private b(string whereto) {


label = whereto;
}

public string readlabel() {


return label;
}
}
return new b(s);
}

public static void main(string[] args) {


mainclass p = new mainclass();
a d = p.dest("a");
}
}

interface a {
string readlabel();
}

5.27.2 import statements

'import' statements must come after the package statement but before the class declaration.
the import keyword can appear multiple times in a class.
import java.io.file;
import java.util.list;

public class demo {

//...
}

5.26.10 multiple interfaces

interface a {
void amethod();
}

interface b {
void bmethod();
}

interface c {
void cmethod();
}

class classa {
public void amethod() {
}
}

class d extends classa implements a, b, c {


public void bmethod() {
}

public void cmethod() {


}
}

public class mainclass {


public static void t(a x) {
x.amethod();
}

public static void u(b x) {


x.bmethod();
}

public static void v(c x) {


x.cmethod();
}

public static void w(classa x) {


x.amethod();
}
public static void main(string[] args) {
d h = new d();
t(h);
u(h);
v(h);
w(h);
}
}

5.25.1 abstract classes

provide a contract between a service provider and its clients.


an abstract class can provide implementation.
to make an abstract method, use the abstract modifier in front of the method declaration.

public abstract class defaultprinter {


public string tostring() {
return "use this to print documents.";
}

public abstract void print(object document);


}

the tostring method has an implementation, so you do not need to override this method.
the print method is declared abstract and does not have a body.

public class myprinter extends defaultprinter {


public void print(object document) {
system.out.println("printing document");
// some code here
}
}

5.17.1 creating objects

using the new keyword.


new is always followed by the constructor of the class.

for example, to create an employee object, you write:

employee employee = new employee();

here, 'employee' is an object reference of type employee.


once you have an object, you can call its methods and access its fields, by using the object
reference.
you use a period (.) to call a method or a field.

for example:

objectreference.methodname
objectreference.fieldname

the following code, for instance, creates an employee object and assigns values to its age and
salary fields:

public class mainclass {

public static void main(string[] args) {


employee employee = new employee();
employee.age = 24;
employee.salary = 50000;
}

class employee {
public int age;
public double salary;
public employee() {
}
public employee(int agevalue, double salaryvalue) {
age = agevalue;
salary = salaryvalue;
}
}

when an object is created, the jvm also performs initialization that assign default values to fields.

5.15.2 comparing objects

when you compare two reference variables a and b, such as in this code

if (a == b)

you are actually asking if a and b are referencing the same object, and not whether or not the
objects referenced by a and b are identical.

consider this example.

yourclass a = new yourclass();


yourclass b = new yourclass();

the type of object 'a' references is identical to the type of object 'b' references. however, a and b
reference two different instances, and a and b contains different memory addresses. therefore, (a
== b) returns false. to compare value for reference use

a.equals(b);

5.14.1 using objects

class point {
double x;

double y;

point(double xval, double yval) {


x = xval;
y = yval;
}

point(final point oldpoint) {


x = oldpoint.x;
y = oldpoint.y;
}

void move(double xdelta, double ydelta) {


x += xdelta;
y += ydelta;
}

double distance(final point apoint) {


return math.sqrt((x - apoint.x) * (x - apoint.x) + (y - apoint.y) * (y - apoint.y));
}

public string tostring() {


return double.tostring(x) + ", " + y;
}
}

// you can use point objects in the definition of the class line:

class line {
point start;

point end;

line(final point start, final point end) {


this.start = new point(start);
this.end = new point(end);
}
line(double xstart, double ystart, double xend, double yend) {
start = new point(xstart, ystart);
end = new point(xend, yend);
}

double length() {
return start.distance(end);
}

public string tostring() {


return "(" + start + "):(" + end + ")";
}
}

public class mainclass{


public static void main(string[] arg){
line l1 = new line(new point(1,2), new point(3,4));

system.out.println(l1);
}

(1.0, 2.0):(3.0, 4.0)

5.15.4 storing a reference to the string object as type object

a variable of type object can store a reference to an object of any class type.

public class mainclass {


public static void main(string[] a) {
string saying = "a stitch in time saves nine.";
object str = saying;
system.out.println(str);
system.out.println(str.getclass().getname());
}
}

a stitch in time saves nine.


java.lang.string

5.19.5 deriving a class


class animal {
public animal(string atype) {
type = atype;
}
public string tostring() {
return "this is a " + type;
}
private string type;
}
class dog extends animal {
public dog(string name){
super(name);
}
private string breed;
}

5.15.6 assignment with objects is a bit tricky.

class number {
int i;
}

public class mainclass {


public static void main(string[] args) {
number n1 = new number();
number n2 = new number();
n1.i = 9;
n2.i = 47;
system.out.println("1: n1.i: " + n1.i + ", n2.i: " + n2.i);
n1 = n2;
system.out.println("2: n1.i: " + n1.i + ", n2.i: " + n2.i);
n1.i = 27;
system.out.println("3: n1.i: " + n1.i + ", n2.i: " + n2.i);
}
}

1: n1.i: 9, n2.i: 47
2: n1.i: 47, n2.i: 47
3: n1.i: 27, n2.i: 27

5.19.8 overriding a base class method

class animal {
public animal(string atype) {
type = new string(atype);
}
public string tostring() {
return "this is a " + type;
}
private string type;
}
class dog extends animal {
public dog(string aname) {
super("dog");
name = aname;
breed = "unknown";
}
public dog(string aname, string abreed) {
super("dog");
name = aname;
breed = abreed;
}
public string tostring() {
return "it's " + name + " the " + breed;
}
private string name;
private string breed;
}

5.19.7 derived class constructors: calling the base class constructor

class animal {
public animal(string atype) {
type = new string(atype);
}
public string tostring() {
return "this is a " + type;
}
private string type;
}
class dog extends animal {
public dog(string aname) {
super("dog");
name = aname;
breed = "unknown";
}
public dog(string aname, string abreed) {
super("dog");
name = aname;
breed = abreed;
}
private string name;
private string breed;
}
5.19.9 type casting

with objects, you can cast an instance of a subclass to its parent class.
casting an object to a parent class is called upcasting.

child child = new child ();


parent parent = child;

to upcast a child object, all you need to do is assign the object to a reference variable of type
parent. the parent reference variable cannot access the members that are only available in child.

because parent references an object of type child, you can cast it back to child. it is called
downcasting because you are casting an object to a class down the inheritance hierarchy.
downcasting requires that you write the child type in brackets. for example:

child child2 = (child) parent;

5.19.10 inheritance, constructors and arguments

class a {
a(int i) {
system.out.println("a constructor");
}
}

class b extends a {
b(int i) {
super(i);
system.out.println("b constructor");
}
}

class c extends b {
c() {
super(11);
system.out.println("c constructor");
}
}

public class mainclass {


public static void main(string[] args) {
c x = new c();
}
}

a constructor
b constructor
c constructor

5.19.14 cleanup and inheritance

// from 'thinking in java, 3rd ed.' (c) bruce eckel 2002


// www.bruceeckel.com. see copyright notice in copyright.txt.

class characteristic {
private string s;

characteristic(string s) {
this.s = s;
system.out.println("creating characteristic " + s);
}

protected void dispose() {


system.out.println("finalizing characteristic " + s);
}
}

class description {
private string s;

description(string s) {
this.s = s;
system.out.println("creating description " + s);
}

protected void dispose() {


system.out.println("finalizing description " + s);
}
}

class livingcreature {
private characteristic p = new characteristic("is alive");

private description t = new description("basic living creature");

livingcreature() {
system.out.println("livingcreature()");
}

protected void dispose() {


system.out.println("livingcreature dispose");
t.dispose();
p.dispose();
}
}

class animal extends livingcreature {


private characteristic p = new characteristic("has heart");

private description t = new description("animal not vegetable");

animal() {
system.out.println("animal()");
}

protected void dispose() {


system.out.println("animal dispose");
t.dispose();
p.dispose();
super.dispose();
}
}

class amphibian extends animal {


private characteristic p = new characteristic("can live in water");

private description t = new description("both water and land");

amphibian() {
system.out.println("amphibian()");
}

protected void dispose() {


system.out.println("amphibian dispose");
t.dispose();
p.dispose();
super.dispose();
}
}

class frog extends amphibian {


private characteristic p = new characteristic("croaks");

private description t = new description("eats bugs");

public frog() {
system.out.println("frog()");
}

protected void dispose() {


system.out.println("frog dispose");
t.dispose();
p.dispose();
super.dispose();
}
}
public class mainclass {

public static void main(string[] args) {


frog frog = new frog();
system.out.println("bye!");
frog.dispose();
}

creating characteristic is alive


creating description basic living creature
livingcreature()
creating characteristic has heart
creating description animal not vegetable
animal()
creating characteristic can live in water
creating description both water and land
amphibian()
creating characteristic croaks
creating description eats bugs
frog()
bye!
frog dispose
finalizing description eats bugs
finalizing characteristic croaks
amphibian dispose
finalizing description both water and land
finalizing characteristic can live in water
animal dispose
finalizing description animal not vegetable
finalizing characteristic has heart
livingcreature dispose
finalizing description basic living creature
finalizing characteristic is alive