2: everything is an object you manipulate objects using references primitives arrays in java scoping...

23
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

Upload: oliver-jenkins

Post on 02-Jan-2016

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 2: Everything is an ObjectYou Manipulate Objects Using ReferencesPrimitivesArrays in JavaScopingYou Never Destroy ObjectsCreating New Data Types: classMethods, Arguments, and Return ValuesNaming ConventionsBuilding a Java ProgramName VisibilityYour First Java ProgramComments & Embedded Documentation

  • 2: Everything is an ObjectBoth C++ and Java are hybrid languagesThe 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 referencesYou manipulate objects with references Java does not support pointer (Syntax)But implemented by pointer (perhaps)String s;// Reference onlyExample: television / file openYou must create all the objectsString s;// s.length() ??String s =new String(ABC); // String s =ABC; Where storage livesRegisterStackHeap

  • String s=new String(ABC);int i=5;sABCi (5) CODE STACK HEAP

  • Special case: primitive types

  • Special case: primitive typesint char float double Wrapper classes : Integer Character char ch=x; Character c= new Character(x);

  • Arrays in JavaObjects (not pointers)Auto boundary checkingC/C++ memory overflowCreationint[ ] aint=new int[5];Array of objects When you create an array of objects, you are really creating an array of referencesIts elements are initialized to nullString[] arr = new String[10]; arr.length;arr[0].length(); //?

  • You never need to destroy an objectScoping (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

    { 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"); }}

    garbage collector Who is responsible for releasing memory: garbage collector

  • Creating new data types: class

  • Creating new data types: classWhen 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 membersThis guarantee doesnt apply to local variablesthose 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

    Sheet1

    Primitive typeDefault

    boolean

    char\u0000 (null)

    byte(byte)0

    short(short)0

    int0

    long0L

    float0.0f

    double0.0d

    Sheet2

    Sheet3

  • Default values for primitive membersclass Data {int i;float f;}class Data {int i=10;float f=1.0;String s=new String(ABC);}

  • Default values for primitive membersclass Data {int i;float f;void func(){int j;int k=2*j;}}

  • Creating new data types: classhow 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 objectmyPlane.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 componentspackage 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 ObjectComments and embedded documentationclass AllTheColorsOfTheRainbow { int anIntegerRepresentingColors; void changeTheHueOfTheColor(int newHue) { // ... } // ...}

  • //: c02:HelloDate.javaimport 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()); }} ///:~

  • HomeworkText p77-90Exercise p1041.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 dont use the argument list. Compile the program with javac and run it using java.