Transcript chap02

2: Everything is an Object
•
•
•
•
•
•
•
•
•
•
•
•
You Manipulate Objects Using References
Primitives
Arrays in Java
Scoping
You Never Destroy Objects
Creating New Data Types: class
Methods, Arguments, and Return Values
Naming Conventions
Building a Java Program
Name Visibility
Your First Java Program
Comments & Embedded Documentation
2: Everything is an Object
Both C++ and Java are hybrid languages
The reason C++ is hybrid is to support backward
compatibility with the C language
Although it is based on C++, Java is more of a
“pure” object-oriented language
You manipulate objects with references
• You manipulate objects with references
– Java does not support pointer (Syntax)
– But implemented by pointer (perhaps)
– String s; // Reference only
• Example: television / file open
• You must create all the objects
– String s;
// s.length() ??
– String s =new String(“ABC”); // String s =“ABC”;
• Where storage lives
– Register
– Stack
– Heap
CODE
STACK
String s=new String(“ABC”);
int i=5;
s
i (5)
“ABC”
HEAP
Special case: primitive types
Primitive
type
Size
Minimum
Maximum
Wrapper type
boolean
—
—
—
Boolean
char
16-bit
Unicode 0
Unicode 2 - 1
Character
byte
8-bit
-128
127
Byte
short
16-bit
-215
+2 —1
int
32-bit
-231
+2 —1
long
64-bit
-263
float
32-bit
double
void
16
15
Short
31
Integer
+2 —1
63
Long
IEEE754
IEEE754
Float
64-bit
IEEE754
IEEE754
Double
—
—
—
Void
Special case: primitive types
– int char float double …
– Wrapper classes : Integer Character …
char ch=‘x’;
Character c= new Character(‘x’);
Arrays in Java
– Objects (not pointers)
– Auto boundary checking
• C/C++ memory overflow
– Creation
• int[ ] aint=new int[5];
– Array of objects
• When you create an array of objects, you are really creating an
array of references
• Its elements are initialized to null
– String[] arr = new String[10];
– arr.length;
– arr[0].length(); //?
You never need to destroy an object
• Scoping (C/C++/Java)
{
int x = 12;
// Only x available
{
int q = 96;
// Both x & q available
}
// Only x available
// q “out of scope”
}
You never need to destroy an object
garbage collector
{ String s = new String("a string"); } /* end of scope */
==========================================
package test;
public class Hello {
public Hello() {
}
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Who is responsible for releasing memory: garbage collector
Creating new data types: class
Creating new data types: class
• When you define a class, you can put two types of
elements in your class:
– fields (sometimes called data members / properties),
– methods (sometimes called member functions).
• If the field is a reference to an object, you must
initialize that reference to connect it to an actual
object
– (using new, as seen earlier) in a special method called a
constructor.
• If it is a primitive type, you can initialize it
directly by assigning a value.
Default values for primitive members
Primitive type
Default
boolean
char
byte
short
int
long
float
double
FALSE
‘\u0000’ (null)
(byte)0
(short)0
0
0L
0.0f
0.0d
This guarantee doesn’t apply to “local” variables—those that are not
fields of a class. Thus, if within a function definition you have:
int x;
Then x will get some arbitrary value (as in C and C++); it will not
automatically be initialized to zero
Default values for primitive members
class Data {
int i;
float f;
}
class Data {
int i=10;
float f=1.0;
String s=new String(“ABC”);
}
Default values for primitive members
class Data {
int i;
float f;
void func(){
int j;
int k=2*j;
}
}
Creating new data types: class
• how to refer to a member of an object
– objectReference.member
– For example:
Feedback
DataOnly d=new DataOnly();
d.i = 47;
d.f = 1.1f;
// ‘f’ after number indicates float constant
d.b = false;
– Objects inside an object
myPlane.leftTank.capacity = 100;
Methods, arguments,
and return values
returnType methodName( /* Argument list */ ) {
/* Method body */
}
• Methods in Java can be created only as part of a
class.
• A method can be called only for an object (Except
for static method)
– objectName.methodName(arg1, arg2, arg3);
– Example: int x = a.f();
• This act of calling a method is commonly referred
to as sending a message to an object. In the
preceding example, the message is f( ) and the
object is a.
Naming Conventions
Name visibility/Using other components
package com.bruceeckel.utility.foibles ;
class AAA {……}
=======================
import com.bruceeckel.utility.foibles.* ;
import java.util.ArrayList;
import java.util.*;
AAA a=new AAA();
=======================
com.bruceeckel.utility.foibles.AAA a=new
com.bruceeckel.utility.foibles.AAA();
java.lang.* is the exception which is needless to
import
First Program:Hello world
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World ! ");
}
}
// HelloWorld.c
int main(int argc,char * argv[]) {
printf("Hello World ! \n");
}
Compiling and running
// HelloDate.java
import java.util.*;
public class HelloDate {
public static void main(String[] args) {
System.out.println("Hello, it's: ");
System.out.println(new Date());
}
}
– javac HelloDate.java
– java HelloDate
2: Everythingis an Object
• Comments and embedded documentation
class AllTheColorsOfTheRainbow {
int anIntegerRepresentingColors;
void changeTheHueOfTheColor(int newHue) {
// ...
}
// ...
}
//: c02:HelloDate.java
import java.util.*;
/** The first Thinking in Java example program.
* Displays a string and today's date.
* @author Bruce Eckel
* @author www.BruceEckel.com
* @version 2.0
*/
public class HelloDate {
/** Sole entry point to class & application
* @param args array of string arguments
* @return No return value
* @exception exceptions No exceptions thrown
*/
public static void main(String[] args) {
System.out.println("Hello, it's: ");
System.out.println(new Date());
}
} ///:~
Homework
• Text p77-90
• Exercise p104
1.Following the HelloDate.java example in this chapter,
create a “hello, world” program that simply prints out
that statement. You need only a single method in your
class (the “main” one that gets executed when the
program starts). Remember to make it static and to
include the argument list, even though you don’t use the
argument list. Compile the program with javac and run
it using java.