Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... ·...

47
Introduction to Java Pengenalan Java Jan Tobochnik and Harvey Gould Jan Tobochnik dan Harvey Gould Java is an object-oriented programming language with a built-in application programming interface (API) that can handle graphics and user interfaces and that can be used to create applications or applets. Java adalah obyek bahasa pemrograman yang berorientasi dengan built-in antarmuka pemrograman aplikasi (API) yang dapat menangani grafis dan antarmuka dan yang dapat digunakan untuk membuat aplikasi atau applet. Because of its rich set of API's, similar to Macintosh and Windows, and its platform independence, Java can also be thought of as a platform in itself. Karena kaya set API's, mirip dengan Macintosh dan Windows, dan independensi platform, Java juga dapat dianggap sebagai platform dalam dirinya sendiri. Java also has standard libraries for doing mathematics. Java juga memiliki perpustakaan standar untuk melakukan matematika. Much of the syntax of Java is the same as C and C++. Sebagian besar sintaks Jawa adalah sama dengan C dan C + +. One major difference is that Java does not have pointers. Salah satu perbedaan utama adalah bahwa Jawa tidak memiliki pointer. However, the biggest difference is that you must write object oriented code in Java. Namun, perbedaan terbesar adalah bahwa Anda harus menulis kode berorientasi objek di Jawa. Procedural pieces of code can only be embedded in objects. Potongan kode prosedural hanya dapat tertanam dalam objek. In the following we assume that the reader has some familiarity with a programming language. Berikut kita mengasumsikan bahwa pembaca memiliki beberapa keakraban dengan bahasa pemrograman. In particular, some familiarity with the syntax of C/C++ is useful. Secara khusus, beberapa keakraban dengan sintaks C / C + + adalah berguna. In Java we distinguish between applications, which are programs that perform the same functions as those written in other programming languages, and applets, which are programs that can be embedded in a Web page and accessed

Transcript of Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... ·...

Page 1: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

Introduction to Java Pengenalan Java Jan Tobochnik and Harvey Gould Jan Tobochnik dan Harvey Gould

Java is an object-oriented programming language with a built-in application programming interface (API) that can handle graphics and user interfaces and that can be used to create applications or applets. Java adalah obyek bahasa pemrograman yang berorientasi dengan built-in antarmuka pemrograman aplikasi (API) yang dapat menangani grafis dan antarmuka dan yang dapat digunakan untuk membuat aplikasi atau applet. Because of its rich set of API's, similar to Macintosh and Windows, and its platform independence, Java can also be thought of as a platform in itself. Karena kaya set API's, mirip dengan Macintosh dan Windows, dan independensi platform, Java juga dapat dianggap sebagai platform dalam dirinya sendiri. Java also has standard libraries for doing mathematics. Java juga memiliki perpustakaan standar untuk melakukan matematika.

Much of the syntax of Java is the same as C and C++. Sebagian besar sintaks Jawa adalah sama dengan C dan C + +. One major difference is that Java does not have pointers. Salah satu perbedaan utama adalah bahwa Jawa tidak memiliki pointer. However, the biggest difference is that you must write object oriented code in Java. Namun, perbedaan terbesar adalah bahwa Anda harus menulis kode berorientasi objek di Jawa. Procedural pieces of code can only be embedded in objects. Potongan kode prosedural hanya dapat tertanam dalam objek. In the following we assume that the reader has some familiarity with a programming language. Berikut kita mengasumsikan bahwa pembaca memiliki beberapa keakraban dengan bahasa pemrograman. In particular, some familiarity with the syntax of C/C++ is useful. Secara khusus, beberapa keakraban dengan sintaks C / C + + adalah berguna.

In Java we distinguish between applications, which are programs that perform the same functions as those written in other programming languages, and applets, which are programs that can be embedded in a Web page and accessed over the Internet. Di Jawa kita membedakan antara aplikasi, yaitu program yang melakukan fungsi yang sama seperti yang ditulis dalam bahasa pemrograman lain, dan applet, yang merupakan program yang dapat tertanam dalam sebuah situs web dan diakses melalui Internet. Our initial focus will be on writing applications. Awal kami akan fokus pada aplikasi penulisan. When a program is compiled, a byte code is produced that can be read and executed by any platform that can run Java. Ketika program dikompilasi, sebuah kode byte yang dihasilkan dapat dibaca dan dieksekusi oleh setiap platform yang dapat menjalankan Java.

To use this tutorial you should run and study each program as you read along, so that you can see how added features affect the programs. Untuk menggunakan tutorial anda harus menjalankan dan mempelajari setiap program saat Anda membaca bersama, sehingga Anda dapat melihat bagaimana menambahkan fitur mempengaruhi program.

Table of Contents Daftar Isi Objects Objects

Constructors Konstruktor

Private variables Variabel

Extending a class Memperluas

Named constants Named

Static methods Metode statis

Page 2: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

pribadi kelas konstanta

String type Tipe string Arrays Array

Methods and Scope Metode dan Ruang Lingkup

Simple graphics Grafik sederhana

Loops Loops

Offscreen Buffer Offscreen Buffer

User Interaction Pengguna Interaksi

Switch Structure Switch Struktur

Animation Animasi

Threads Threads

Utility Package Utilitas Paket

ControlFrame ControlFrame

ControlMenu ControlMenu Table Meja Plot Plot WorldGraphics

WorldGraphics

Syntax Summary Sintaks Ringkasan

References Referensi

Objects Objects

Object-oriented programming focuses on constructs called “objects.” An object consists of data and functions known as methods which use or change the data. Pemrograman berorientasi obyek berfokus pada konstruksi yang disebut "obyek." Sebuah benda terdiri dari data dan fungsi-fungsi yang dikenal sebagai metode yang menggunakan atau mengubah data. (Methods are similar to procedures or functions in other languages.) Objects of the same kind are said to have the same type or be in the same class. (Metode ini mirip dengan prosedur atau fungsi dalam bahasa lain.) Obyek dari jenis yang sama dikatakan memiliki tipe yang sama atau berada di kelas yang sama. A class defines what data can be in an object, and what operations are performed by the methods. Sebuah kelas mendefinisikan data apa yang dapat diberikan dalam obyek, dan operasi apa yang dilakukan oleh metode. One or more objects can be created or “instantiated” from a class. Satu atau lebih objek dapat diciptakan atau "instantiated" dari sebuah kelas. The structure of a Java program consists of various objects exchanging messages. Struktur dari sebuah program Java terdiri dari berbagai objek bertukar pesan. The keyword class defines a blueprint for objects with similar properties. Mendefinisikan kelas kata kunci cetak biru untuk benda dengan sifat yang sama. In our first example we define the class Particle . Dalam contoh pertama kita mendefinisikan kelas partikel. public class Particle { double x, y, vx, vy, mass; } public class Particle (double x, y, vx, vv, massa;)

This class does not do anything (because it has no methods), but it can be used to describe a particle by its position, velocity, and mass. Kelas ini tidak melakukan apa-apa (karena tidak memiliki metode), tetapi dapat digunakan untuk menggambarkan sebuah partikel oleh posisi, kecepatan, dan massa. For simplicity, we will consider only two dimensions. Untuk mempermudah, kita hanya akan membahas dua dimensi.

Constructors Konstruktor

Every class has at least one constructor, a method which has the same name as the class. Setiap kelas memiliki paling sedikit satu konstruktor, sebuah metode yang

Page 3: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

memiliki nama yang sama dengan kelas. A constructor initializes a new object belonging to the class. Sebuah konstruktor menginisialisasi objek baru milik kelas. public class Particle { double x, y, vx, vy, mass; // these variables can be used by any method in the class // example of constructor method public Particle(double x, double y, double vx, double vy, double mass) { /* Use this keyword to make explicit that a method is accessing its own variables. public class Particle (double x, y, vx, vv, massa; / / variabel-variabel tersebut dapat digunakan oleh metode apapun di kelas / / contoh metode konstruktor Particle publik (double x, double y, double vx, double vy, double massa) (/ * Gunakan kata kunci ini untuk membuat eksplisit bahwa metode mengakses variabel sendiri. */ this.x = x; // set instance variable x equal to value of x in parameter list this.y = y; this.vx = vx; this.vy = vy; this.mass = mass; } } * / This.x = x; / / set contoh variabel x sama dengan nilai x dalam daftar parameter this.y = y; this.vx = vx; this.vy = vy; this.mass = massa;))

The constructor Particle creates an object of the Particle class by specifying five parameters: the initial position and velocity of a particle and the value of its mass. Particle constructor menciptakan sebuah objek dari kelas partikel dengan menetapkan lima parameter: posisi awal dan kecepatan dari sebuah partikel dan nilai massanya. We say that Particle is the constructor for the Particle class. Kita mengatakan bahwa partikel adalah constructor untuk kelas partikel.

We have used the following properties of Java: Kami telah menggunakan sifat-sifat berikut Jawa:

Variable Declaration: The types of all variables must be declared. Deklarasi Variabel: Jenis dari semua variabel harus dinyatakan. The primitive types are byte , short , int , long (8, 16, 32, and 64 bit integer variables, respectively), float and double (32 and 64-bit floating point variables), boolean (true or false), and char . Boolean is a distinct type rather than just another way of using integers. Tipe primitif byte, pendek, int, panjang (8, 16, 32, dan 64 bit integer variabel, masing-masing), float dan double (32 dan 64-bit floating point variabel), boolean (true atau false), dan char . Boolean adalah tipe yang berbeda bukan hanya cara lain untuk menggunakan bilangan bulat. Strings are not a primitive type, but are instances of the String class. String bukan merupakan tipe primitif, tetapi contoh dari String kelas. Because they are so common, string literals may appear in quotes just as in other languages. Summary of primitive data types . Karena mereka begitu umum, string literal mungkin muncul dalam tanda kutip seperti dalam bahasa lain. Ringkasan tipe data primitif.

Page 4: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

Naming Conventions: Java distinguishes between upper and lower case variables. Konvensi Penamaan: Jawa membedakan antara huruf besar dan kecil variabel. The convention is to capitalize the first letter of a class name. Konvensi adalah untuk memanfaatkan huruf pertama dari nama kelas. If the class name consists of several words, they are run together with successive words capitalized within the name (instead of using underscores to separate the names). Jika nama kelas terdiri dari beberapa kata, mereka dijalankan bersama-sama dengan kata-kata yang berurutan huruf dalam namanya (bukan menggunakan menekankan untuk memisahkan nama-nama). The name of the constructor is the same as the name of the class. Nama constructor sama dengan nama kelas. All keywords (words that are part of the language and cannot be redefined) are written in lower case. Semua kata kunci (kata-kata yang merupakan bagian dari bahasa dan tidak dapat didefinisikan ulang) ditulis dalam huruf kecil.

Instance variables and methods can be accessed from any method within the class. Misalnya variabel dan metode dapat diakses dari metode apapun dalam kelas. The x in the argument list of the above constructor refers to the local value of the parameter which is set when Particle is called. The x pada daftar argumen constructor di atas mengacu pada nilai lokal dari parameter yang ditetapkan saat partikel disebut. We use the this keyword to refer to those variables defined for the entire class in contrast to those defined locally within a method and those that are arguments to a method. Kita menggunakan kata kunci ini untuk merujuk kepada orang-variabel yang ditetapkan untuk seluruh kelas berbeda dengan yang ditetapkan secara lokal di dalam metode dan yang memiliki argumen untuk sebuah metode. In the above example, this.x refers to the variable x which is defined just after the first line of the class definition. Dalam contoh di atas, this.x mengacu pada variabel x yang didefinisikan hanya setelah baris pertama dari definisi kelas. After we have introduced multiple constructors , we show a more iillustrative example of the this keyword. Setelah kami telah memperkenalkan beberapa constructor, kami tunjukkan yang lebih iillustrative contoh tentang kata kunci ini.

Classes are effectively new programmer-defined types; each class defines data (fields) and methods to manipulate the data. Kelas secara efektif baru didefinisikan pemrogram-jenis; masing-masing kelas mendefinisikan data (bidang) dan metode untuk memanipulasi data. Fields in the class are template for the instance variables that are created when objects are instantiated (created) from that class. Bidang dalam kelas template untuk contoh variabel yang dibuat ketika objek instantiated (diciptakan) dari kelas. A new set of instance variables is created each time that an object is instantiated from the class. Set baru instance variable yang dibuat setiap kali sebuah objek instantiated dari kelas.

The members of a class (variables and methods) are accessed by referrring to an object created from thr clas using the dot operator . Anggota kelas (variabel dan metode) yang diakses oleh referrring ke suatu objek yang dibuat dari thr Clas menggunakan operator dot. For example, suppose that a class Particle contains and instance variable x amd a method step . Sebagai contoh, anggaplah bahwa suatu kelas partikel berisi dan contoh variabel x amd sebuah metode langkah. If an object of this class is named p , then

Page 5: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

the instance variable in p would be accessed as px and the method accessed as p.step . Jika suatu objek kelas ini bernama p, maka p contoh variabel akan diakses sebagai px dan metode diakses sebagai p.step.

A semicolon is used to terminate individual statements. Suatu titik koma digunakan untuk menghentikan pernyataan individu.

Comments . Comments. There are three comment styles in Java. Ada tiga gaya komentar di Jawa. A single line comment starts with // and can be included anywhere in the program. Satu baris komentar dimulai dengan / / dan dapat dimasukkan di mana saja dalam program. Multiple line comments begin with /* and end with */ ; these are also useful for commenting out a portion of the text on a line. Beberapa baris komentar dimulai dengan / * dan diakhiri dengan * /; ini juga berguna untuk komentar dari sebagian teks pada baris. Finally, text enclosed within /** ... Akhirnya, teks tertutup dalam / ** ... */ serves to generate documentation using the javadoc command. * / Berfungsi untuk menghasilkan dokumentasi menggunakan perintah javadoc.

Assignments . Penugasan. Java uses the C/C++ shortcuts summarized in Table 2. Java menggunakan C / C + + pintas diringkas dalam Tabel 2.

Table 2. Tabel 2. Assignment shortcuts. Assignment pintas.

operator operator

example contoh meaning makna

+= + = x += y x + = y x = x + y x = x + y -= -= x -= y x -= y x = x - y x = x - y *= *= x *= y x *= y x = x*y x = x * y /= = x /= y x / = y x = x/y x = x / y

%= % = x %= y x% = y x = x % y x = x% y

The modulus operator % returns the remainder of a division. Modulus operator% mengembalikan sisa divisi. For example, 5 % 3 returns 2. Sebagai contoh, 5% 3 kembali 2. The increment operator ++ works as follows: The increment operator + + bekerja sebagai berikut:

i++; i + +;

is equivalent to setara dengan

i = i + 1; i = i + 1;

Similarly, the decrement operator -- works as follows: Demikian pula, operator pengurangan - bekerja sebagai berikut:

i--; i -;

is equivalent to setara dengan

Page 6: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

i = i - 1; i = i - 1; Type casting changes the type of a value from its normal type to some other

type. Jenis perubahan casting jenis nilai dari jenis normal untuk beberapa jenis lain. For example: Contoh:

double distance; distance = 10.0; int x; x = (int)distance; // example of a type cast jarak ganda; jarak = 10,0; int x; x = (int) jarak; / / contoh dari tipe cast

What would be the value of x in the above example if distance = 9.9? Apa yang akan menjadi nilai x pada contoh di atas jika jarak = 9,9?

Multiple Constructors Multiple Konstruktor

The arguments of a constructor specify the parameters for the initialization of an object. Argumen dari konstruktor menentukan parameter untuk inisialisasi objek. Multiple constructors provide the flexibility of initializing objects in the same class with different sets of arguments, as in the following example. Multiple konstruktor menyediakan fleksibilitas menginisialisasi objek dalam kelas yang sama dengan set yang berbeda argumen, seperti dalam contoh berikut. public class Particle { double x, y, vx, vy, mass; // examples of multiple constructors public Particle() { this(0.0,0.0); } public Particle(double x, double y) { this(x,y,1.0); } public Particle(double x, double y, double m) { this(x,y,0.0,0.0,m); } public Particle(double x, double y, double vx, double vy) { this(x,y,vx,vy,1.0); } public Particle(double x, double y, double vx, double vy, double mass) { this.x = x; this.y = y; this.vx = vx; this.vy = vy; this.mass = mass; } } public class Particle (double x, y, vx, vv, massa; / / contoh dari beberapa konstruktor Particle publik () (ini (0.0,0.0);) public Particle (double x, double y) (ini (x, y, 1,0);) public Particle (double x, double y, double m) (ini (x, y, 0.0,0.0, m);) public Particle (double x, double y, double vx, double vy) (ini (x , y, vx, vv, 1,0);) public Particle (double x, double y, double vx, double vy, double massa) (this.x = x; this.y = y; this.vx = vx; ini. vy = vy; this.mass = massa;)) The multiple constructors (all named Particle) are distinguished only by the

number of arguments. Konstruktor ganda (semua bernama Particle) hanya dibedakan oleh jumlah argumen. The constructors can be defined in any order. Yang konstruktor dapat didefinisikan dalam urutan apapun. Hence, the

Page 7: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

keyword this in the first constructor refers to the next in the sequence because the latter has two arguments. Oleh karena itu, kata kunci ini dalam constructor pertama mengacu pada urutan berikutnya karena terakhir telah dua argumen. The first constructor has no arguments and creates a particle of unit mass at the origin; the next is defined with two arguments: the spatial coordinates of the particle. Pertama constructor tidak mempunyai argumen dan menciptakan partikel satuan massa di titik asal; berikutnya didefinisikan dengan dua argumen: koordinat spasial partikel. The second constructor in turn references the third constructor which uses the spatial coordinates and the mass. Constructor kedua pada gilirannya referensi constructor ketiga yang menggunakan koordinat ruang dan massa. The third and fourth constructors each refer to the final constructors which uses all five arguments. Ketiga dan keempat masing-masing konstruktor merujuk ke final konstruktor yang menggunakan argumen kelima. (The order of the constructors is unimportant.) Once the Particle class with its multiple constructors is defined, any class can call the constructor Particle using the number of arguments appropriate to that application. (Urutan konstruktor tidak penting.) Begitu kelas partikel dengan beberapa constructor ditetapkan, setiap kelas dapat memanggil constructor Particle menggunakan sejumlah argumen yang sesuai dengan aplikasi tersebut. The advantage of having multiple constructors is that applications that use a particular constructor are unaffected by later additions made to the class Particle , whether variables or methods. Keuntungan memiliki beberapa constructor adalah bahwa aplikasi yang menggunakan constructor tertentu yang tidak terpengaruh oleh penambahan kemudian dibuat untuk kelas partikel, apakah variabel atau metode. For example, adding acceleration as an argument does not affect applications that rely only on the definitions given above. Misalnya, menambahkan percepatan sebagai argumen tidak mempengaruhi aplikasi yang mengandalkan hanya pada definisi yang diberikan di atas.

Using multiple constructors is called method overloading -- the method name is used to specify more than one method. Menggunakan beberapa metode konstruktor disebut overloading - nama metode digunakan untuk menentukan lebih dari satu metode. The rule for overloading is that the argument lists for all of the different methods must be unique, including the number of arguments and/or the types of the arguments. Aturan untuk overloading adalah bahwa daftar argumen untuk semua metode yang berbeda harus unik, termasuk jumlah argumen dan / atau jenis argumen.

All classes have at least one implicit constructor method. Semua kelas memiliki minimal satu metode implisit konstruktor. If no constructor is defined explicitly, the compiler creates one with no arguments. Jika tidak ada konstruktor yang didefinisikan secara eksplisit, compiler menciptakan satu tanpa argumen.

We next give an example of a Particle class with methods for computing the weight of a particle and its distance from the origin. Selanjutnya kami memberikan contoh sebuah kelas partikel dengan metode untuk menghitung berat partikel dan jarak dari titik asal. We will omit the velocity components for now. Kami akan menghilangkan komponen kecepatan untuk saat ini.

Page 8: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

public class Particle { double x, y, mass; public Particle() { } public Particle(double x, double y) { this(x,y,1); } public Particle(double x, double y, double mass) { this.x = x; this.y = y; this.mass = mass; } public double getWeight() { return 9.8*mass; } public double distanceFromOrigin() { return Math.sqrt(x*x + y*y); } } public class Particle (double x, y, massa public Particle () () public Particle (double x, double y) (this (x, y, 1);) public Particle (double x, double y, double massa) ( this.x = x; this.y = y; this.mass = massa;) public double getWeight () (return 9,8 * massa;) public double distanceFromOrigin () (return Math.sqrt (x * x + y * y) ;)) 1. The fundamental parts of a method are its name, arguments, return type, and

the body. Bagian fundamental dari suatu metode yang namanya, argumen, kembali jenis, dan tubuh. Methods can be created only as part of a class. Metode dapat dibuat hanya sebagai bagian dari sebuah kelas. By convention, variable and method names begin with a lower case letter. Dengan konvensi, variabel dan nama metode yang dimulai dengan huruf kecil huruf.

2. The keyword return followed by an expression returns the value of the expression to the caller of the method. Kata kunci return diikuti oleh suatu ekspresi mengembalikan nilai ke pemanggil ekspresi dari metode. The type of the expression must be the same as specified by the method. Tipe ekspresi harus sama seperti yang ditentukan oleh metode. (Note that a constructor does not return a value and hence no type is specified.) A method can return only the value of a single expression. (Perhatikan bahwa constructor tidak mengembalikan nilai sehingga tidak ada jenis ditentukan.) Sebuah metode hanya dapat mengembalikan nilai ekspresi tunggal.

3. The method distanceFromOrigin in the class Particle computes the distance of a particle from the origin using the particle coordinates x and y. Metode di kelas distanceFromOrigin Particle menghitung jarak partikel dari titik asal menggunakan partikel koordinat x dan y. The square root function Math.sqrt in this calculation is part of the Math class, a library of mathematical functions which consists of a collection of static methods. Fungsi akar kuadrat Math.sqrt dalam perhitungan ini adalah bagian dari kelas Math, perpustakaan fungsi matematika yang terdiri dari koleksi statis metode. We will postpone a discussion of such classes, but their use is clear from the context. Kami akan menunda diskusi kelas tersebut, tetapi penggunaannya jelas dari konteks.

A program consists of one or more class definitions, each of which should be in separate files. Suatu program terdiri dari satu atau lebih definisi kelas, masing-masing harus dalam berkas terpisah. The name of the file should be the same as the name of

Page 9: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

the class, for example, MyApplication.java. Nama file harus sama dengan nama kelas, misalnya, MyApplication.java. One of these classes must define a method main . Salah satu kelas harus mendefinisikan sebuah metode main.

The following program creates two objects of type Particle . Program berikut ini akan menciptakan dua jenis partikel objek.

public class MyApplication { public static void main(String[] args) { /* Need an instance of class Particle - a particle object; assign it to the variable a which is of type Particle. public class MyApplication (public static void main (String [] args) (/ * Perlu sebuah instance dari kelas partikel - partikel objek; assign ke suatu variabel yang bertipe Particle. */ Particle a = new Particle(1.0,1.0); System.out.println("Distance of particle a from origin = " + a.distanceFromOrigin()); System.out.println("Mass of particle a = " + a.mass); Particle b = new Particle(); bx = 2.0; by = 3.0; b.mass = 3; System.out.println("Distance of particle b from origin = " + b.distanceFromOrigin()); System.out.println("Mass of particle b = " + b.mass); System.out.println("Weight of particle b = " + b.getWeight()); } } * / Partikel partikel baru a = (1.0,1.0); System.out.println ( "Jarak partikel a dari asal =" + a.distanceFromOrigin ()); System.out.println ( "Massa partikel a =" + a.mass); partikel partikel b = new (); bx = 2.0; oleh = 3.0; b.mass = 3; System.out.println ( "Jarak partikel b dari asal =" + b.distanceFromOrigin ()); ; System.out.println ( "Massa partikel b =" + b.mass); System.out.println ( "Berat partikel b =" + b.getWeight ());)) The first statement in main declares a to be a Particle and uses the new

keyword to instantiate an object. Pernyataan pertama dalam mengumumkan utama menjadi partikel dan menggunakan kata kunci baru untuk instantiate sebuah obyek. These two operations could have been done separately in two lines as illustrated for Particle b . Kedua operasi bisa dilakukan secara terpisah dalam dua baris seperti yang diilustrasikan untuk partikel b. Note that Java already defines primitive data types such as int and double . Perhatikan bahwa Jawa sudah mendefinisikan tipe data primitif seperti int dan double.

Page 10: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

If a program has more than one class, one and only one of the classes must define main() . Jika sebuah program memiliki lebih dari satu kelas, satu dan hanya satu dari kelas harus mendefinisikan main ().

The statement System.out.println() allows us to print the argument to the standard output with a call to the System class . System.out is an object used for sending output to the screen and println is a method that this object invokes. Pernyataan System.out.println () memungkinkan kita untuk mencetak argumen ke standar output dengan panggilan ke kelas Sistem. System.out adalah obyek yang digunakan untuk mengirimkan output ke layar dan println adalah metode yang memanggil objek ini.

Public and Private Variables Publik dan Swasta Variabel

Java uses three explicit keywords and one implied keyword to set the boundaries in a class: public , private , and protected . Java menggunakan tiga eksplisit tersirat kata kunci dan satu kata kunci untuk menetapkan batas-batas dalam kelas: publik, swasta, dan dilindungi. The default access specifier for the names of variables and methods is “package visibility” or “friendly,” which means that all the other classes in the current package have access to them. Specifier akses standar untuk nama-nama variabel dan metode adalah "paket visibilitas", atau "ramah," yang berarti bahwa semua kelas-kelas lain dalam paket saat ini memiliki akses kepada mereka. (Packages are Java's way of grouping classes to make libraries and will be discussed later.) The access specifier public means that the variables and methods are available from any package; private implies that the variables and methods can only be accessed inside methods of the same class. (Paket-paket Jawa cara pengelompokan kelas untuk membuat perpustakaan dan akan dibicarakan nanti.) Specifier akses publik berarti bahwa variabel-variabel dan metode yang tersedia dari setiap paket; swasta menunjukkan bahwa variabel-variabel dan metode hanya bisa diakses dalam metode yang sama kelas. The keyword protected indicates additional access to variables and methods that are available to subclasses. Kata kunci tambahan yang dilindungi menunjukkan akses ke variabel dan metode yang tersedia untuk subclass. We will clarify its meaning when we discuss inheritance . Kita akan memperjelas makna ketika kita membicarakan warisan.

One reason to make a variable private is to restrict access to it. Salah satu alasan untuk membuat sebuah variabel pribadi adalah untuk membatasi akses ke sana. Access becomes an issue for threading which refers to the sequence of execution of program code. Akses menjadi masalah bagi threading yang mengacu pada urutan eksekusi kode program. For example, we would want to avoid changing the value of a variable while another portion of the code is trying to read it. Sebagai contoh, kita ingin menghindari mengubah nilai dari variabel sementara bagian lain dari kode sedang mencoba untuk membacanya. Make x private and see what happens when you run MyApplication . Membuat x swasta dan melihat apa yang terjadi ketika Anda menjalankan MyApplication.

If we declare x, y, and mass as private variables, we have to include explicit methods in Particle to allow another class to access the variable information in Particle . Jika kita menyatakan x, y, dan massa sebagai variabel pribadi, kita

Page 11: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

harus menyertakan metode eksplisit dalam partikel untuk memungkinkan kelas lain untuk mengakses informasi dalam Particle variabel. For simplicity, we will consider only the variables x and mass. Untuk mempermudah, kita hanya akan mempertimbangkan variabel x dan massa. Our Particle class becomes: Kelas partikel kami menjadi:

public class Particle { private double x; private double mass; public Particle(double x) { this(x, 1.0); } public Particle(double x, double mass) { this.x = x; this.mass = mass; } public double getX() { return x; } public void setX(double newX) { x = newX; } public double getWeight() { return 9.8*mass; } public double distanceFromOrigin() { return Math.abs(x); } } public class Particle (private double x; private double massa public Particle (double x) (ini (x, 1,0);) public Particle (double x, double massa) (this.x = x; this.mass = massa;) public double getX () (return x;) public void setX (double newX) (x = newX;) public double getWeight () (return 9,8 * massa;) public double distanceFromOrigin () (return Math.abs (x);) )

Note the new methods getX and setX. Catatan getX metode baru dan setX. They are used in the following. Mereka digunakan sebagai berikut.

public class MyApplication { public static void main(String[] args) { Particle p = new Particle(10.0, 2.0); System.out.println("Distance of particle from origin = " + p.distanceFromOrigin()); System.out.println("x-coordinate = " + p.getX()); // would have written px if x were public System.out.println(weight = " + p.getWeight()); p.setX(3.0); // change value of x System.out.println("new x-coordinate = " + p.getX()); System.out.println("new distance from origin = " + p.distanceFromOrigin()); } } public class MyApplication (public static void main (String [] args) (p = partikel partikel baru (10.0, 2.0); System.out.println ( "Jarak partikel dari asal =" + p.distanceFromOrigin ()); System. out.println ( "x-koordinat =" + p.getX ()); / / akan ditulis px jika x adalah publik System.out.println (berat = "+

Page 12: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

p.getWeight ()); p.setX (3,0 ); / / ubah nilai x System.out.println ( "baru x-koordinat =" + p.getX ()); System.out.println ( "baru jarak dari asal =" + p.distanceFromOrigin ()); ))

In the following, we will not make variables such as x and y private, because they will be used in so many classes. Dalam berikut, kita tidak akan membuat variabel seperti x dan y swasta, karena mereka akan digunakan dalam begitu banyak kelas.

Using the Particle class Menggunakan kelas Particle

We now redefine the class Particle to include a method to compute the distance between two particles. Kita sekarang mendefinisikan kembali kelas partikel untuk menyertakan sebuah metode untuk menghitung jarak antara dua partikel. The application that follows creates two particles and gives their mutual separation. Aplikasi yang berikut menciptakan dua partikel dan memberi mereka saling berpisah. public class Particle { double x, y, mass; public Particle(double x, double y) { this(x, y, 1.0); } public Particle(double x, double y, double mass) { this.x = x; this.y = y; this.mass = mass; } public double distanceFrom(Particle a) { double r2 = Math.pow(this.x - ax, 2) + Math.pow(this.y - ay,2); return Math.sqrt(r2); } public double distanceFromOrigin() { return Math.sqrt(x*x + y*y); } } public class Particle (double x, y, massa public Particle (double x, double y) (this (x, y, 1,0);) public Particle (double x, double y, double massa) (this.x = x; this.y = y; this.mass = massa;) public double distanceFrom (Particle a) (double r2 = Math.pow (this.x - ax, 2) + Math.pow (this.y - ay, 2); return Math.sqrt (r2);) public double distanceFromOrigin () (return Math.sqrt (x * x + y * y);)) public class MyApplication { public static void main(String[] args) { Particle a = new Particle(5.0, 7.0); Particle b = new Particle(1.0, 2.0); System.out.println("Distance of a from b = " + a.distanceFrom(b)); System.out.println("Distance of b from a = " + b.distanceFrom(a)); } } public class MyApplication (public static void main (String [] args) (partikel partikel a = baru (5,0, 7,0); partikel partikel b = baru (1.0, 2.0); System.out.println ( "Jarak dari dari b = "+

Page 13: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

a.distanceFrom (b)); System.out.println (" Jarak b dari a = "+ b.distanceFrom (a));))

Extending a class Memperluas kelas

Object oriented programming allows the user to reuse existing code rather than rewrite it. Pemrograman berorientasi obyek memungkinkan pengguna untuk menggunakan kembali kode yang sudah ada daripada menuliskannya kembali. Classes have a hierarchical relationship, allowing the user to extend or modify the behavior of classes derived from base classes using inheritance. For example, we can expand the Particle class to include charged particles. Kelas memiliki hubungan hirarkis, yang memungkinkan user untuk memperpanjang atau memodifikasi perilaku kelas diturunkan dari kelas dasar menggunakan warisan. Sebagai contoh, kita dapat memperluas kelas untuk menyertakan partikel partikel bermuatan. The new class ChargedParticle will combine all the behavior and functionality of Particle with the ability to have a charge. ChargedParticle kelas baru akan menggabungkan semua perilaku dan fungsi dari partikel dengan kemampuan untuk memiliki biaya. We can implement ChargedParticle as an extension of Particle as shown below. Kita dapat menerapkan ChargedParticle sebagai perpanjangan dari partikel seperti yang ditunjukkan di bawah ini. public class ChargedParticle extends Particle { // magnitude of electron charge in Coulombs public static final double ELQ = 1.602e-19; private int charge; public ChargedParticle(double x,double y, double mass, int charge) { super(x, y, mass); // constructor for Particle this.charge = charge; } public int getCharge() { return charge*ELQ; } public void setCharge(int newCharge) { charge = newCharge; } public static int netCharge(ChargedParticle a, ChargedParticle b) { return a.charge + b.charge; } } public class extends ChargedParticle Particle (/ / besarnya muatan elektron dalam coulomb public static final double ELQ = 1.602e-19; private int biaya; ChargedParticle publik (double x, double y, double massa, muatan int) (super (x, y , massa); / / konstruktor untuk Particle this.charge = biaya;) public int getCharge () (return muatan * ELQ;) public void setCharge (int newCharge) (biaya = newCharge;) public static int netCharge (ChargedParticle a, ChargedParticle b) (return a.charge + b.charge;))

An example of the use of this new class is given below. Contoh penggunaan kelas baru ini diberikan di bawah ini.

Page 14: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

public class MyApplication { public static void main(String[] args) { // particle charge is expressed in units of electron charge ChargedParticle a = new ChargedParticle(10.0,0,0,1); System.out.println("distance of a from origin = " + a.distanceFromOrigin()); System.out.println("charge of a = " + a.getCharge()); System.out.println("charge of a in coulombs = " + ChargedParticle.ELQ*a.getCharge()); ChargedParticle b = new ChargedParticle(-5.0,0,0,-1); System.out.println("distance of b from origin: " + b.distanceFromOrigin()); System.out.println("charge of b = " + b.getCharge()); System.out.println("net charge of a and b = " + ChargedParticle.netCharge(a,b)); b.setCharge(3); System.out.println("new charge of b = " + b.getCharge()); System.out.println("net charge of a and b = " + ChargedParticle.netCharge(a,b)); } } public class MyApplication (public static void main (String [] args) (/ / partikel muatan dinyatakan dalam satuan muatan elektron ChargedParticle a = ChargedParticle baru (10.0,0,0,1); System.out.println ( "jarak a dari asal = "+ a.distanceFromOrigin ()); System.out.println (" memimpin sebuah = "+ a.getCharge ()); System.out.println (" memimpin sebuah di coulomb = "+ ChargedParticle. ELQ * a.getCharge ()); ChargedParticle b = new ChargedParticle (-5.0,0,0, -1); System.out.println ( "jarak b dari asal:" + b.distanceFromOrigin ()); System. out.println ( "bertanggung jawab atas b =" + b.getCharge ()); System.out.println ( "net bertanggung jawab atas a dan b =" + ChargedParticle.netCharge (a, b)); b.setCharge (3) ; System.out.println ( "tuduhan baru b =" + b.getCharge ()); System.out.println ( "net bertanggung jawab atas a dan b =" + ChargedParticle.netCharge (a, b));))

Note how the (named) constant ELQ , the charge of an electron, has been introduced. Perhatikan bagaimana (bernama) konstan ELQ, tuduhan elektron, telah diperkenalkan.

The keyword super refers to the constructor of the base class, in this case Particle . Super kata kunci mengacu pada constructor dari kelas dasar, dalam hal ini partikel. An inherited subclass contains all the members of the superclass except the private ones. Sebuah subclass mewarisi berisi semua

Page 15: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

anggota SUPERCLASS kecuali orang-orang swasta. Thus a derived class can receive the same messages as a base class. Jadi kelas turunan dapat menerima pesan yang sama sebagai dasar kelas.

A variable declared final is a constant. Sebuah variabel dinyatakan terakhir adalah sebuah konstanta. Its value must be specified when it is declared and this value cannot be changed. Nilainya harus ditentukan ketika dinyatakan dan nilai ini tidak dapat diubah. The static keyword means that there is only one copy of this variable, regardless of the number of instances of the class that are created. Kunci statis berarti bahwa hanya ada satu salinan dari variabel ini, terlepas dari jumlah instance dari kelas yang dibuat. (A better name is class variable.) The C convention of using CAPITAL letters for constants will be used whenever it will not cause confusion. (Nama yang lebih baik adalah variabel kelas.) C MODAL konvensi menggunakan huruf untuk konstanta yang akan digunakan setiap kali tidak akan menimbulkan kebingungan.

The method setCharge defines the behavior of a particular object. Metode setCharge mendefinisikan perilaku objek tertentu. In contrast, the static method netCharge belongs to the class and not to a particular instantiation of the class. Sebaliknya, metode statis netCharge termasuk kelas dan bukan untuk Instansiasi tertentu dari kelas. To call a static method we use the class name rather than an instance name. Untuk memanggil metode statis kita menggunakan nama kelas dan bukan nama contoh. Thus, to call the method netCharge we use ChargedParticle.netCharge(a,b) not a.netCharge(a,b) . Jadi, untuk memanggil metode netCharge kita gunakan ChargedParticle.netCharge (a, b) tidak a.netCharge (a, b). A static method is equivalent to a global function in C. Sebuah metode statis ekuivalen dengan fungsi global di C.

Static methods (class methods) and static variables, belong to a class and not a given instance of the class. Metode static (metode kelas) dan variabel statis, termasuk kelas dan bukan contoh yang diberikan di kelas. The following example illustrates the nature of static variables: Contoh berikut menggambarkan sifat variabel statis: public class StaticTest { public static int x = 0; public int y = 0; public String getCoordinates() { return "x = " + x + ", y = " + y; } public static void main(String[] args) { StaticTest a = new StaticTest(); StaticTest b = new StaticTest(); ax = 5; // static variable ay = 12; // instance variable System.out.println(a.getCoordinates()); // outputs 5, 12 bx = 7; by = 13; System.out.println(a.getCoordinates()); // outputs 7, 12 System.out.println(b.getCoordinates()); // outputs 7, 13 StaticTest.x = 2; System.out.println(a.getCoordinates()); // outputs 2, 12 System.out.println(b.getCoordinates()); //

Page 16: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

outputs 2, 13 } } public class StaticTest (public static int x = 0; public int y = 0; public String getCoordinates () (return "x =" + x + ", y =" + y;) public static void main (String [] args) (StaticTest a = new StaticTest (); StaticTest b = new StaticTest (); ax = 5; / / static variabel ay = 12; / / contoh variabel System.out.println (a.getCoordinates ()); / / output 5 , 12 bx = 7; oleh = 13; System.out.println (a.getCoordinates ()); / / output 7, 12 System.out.println (b.getCoordinates ()); / / output 7, 13 StaticTest. x = 2; System.out.println (a.getCoordinates ()); / / output 2, 12 System.out.println (b.getCoordinates ()); / / output 2, 13))

The (static) x member belongs to class Test and hence belongs to a and b. The (statis) x anggota kelas milik Test dan karenanya milik a dan b. There is only one variable x and thus the value of x is always the one most recently specified. Hanya ada satu variabel x dan dengan demikian nilai x adalah selalu yang paling baru-baru ini ditentukan. In contrast, y belongs to the instances a and b of the class Test and hence ay and by are distinct variables. Sebaliknya, y termasuk dalam contoh a dan b dari kelas Test dan karena itu ay dan variabel yang berbeda.

The String type is unique among all classes because it is the only class to support an operator: the + operator can be used to concatenate strings. Jenis String unik di antara semua kelas karena merupakan satu-satunya kelas untuk mendukung operator: operator + dapat digunakan untuk menggabungkan string. When a number is concatenated with a string, the number is converted to a string. Ketika sebuah nomor concatenated dengan sebuah string, jumlah dikonversi menjadi string. Because a String variable is an object, it has methods. Karena variabel String adalah objek, itu metode. (The class String is different than other classes.) Some of its associated methods are summarized in Table 4 . (String kelas berbeda dari kelas-kelas lain.) Beberapa metode yang berhubungan dirangkum dalam Tabel 4.

Arrays Array

An array is a special object containing a group of contigious memory locations that have the same name and the same type and a separate variable containing an integer constant equal to the number of array elements. Sebuah array adalah objek khusus yang berisi sekelompok contigious lokasi memori yang memiliki nama yang sama dan tipe yang sama dan variabel yang terpisah yang berisi sebuah integer konstanta yang sama dengan jumlah elemen array. The elements of Java arrays are numbered starting from 0. Unsur-unsur Jawa array diberi nomor mulai dari 0.

An array must be created before it can be used. Array harus diciptakan sebelum dapat digunakan. We first declare a reference or "handle" to an array that permits Java to locate the object in memory when it is needed. Kami pertama-tama menyatakan referensi atau "menangani" ke array yang memungkinkan Jawa untuk menemukan objek dalam memori ketika diperlukan. Then we create an array object to assign to the reference using the new operator. Lalu kita membuat sebuah array objek yang akan

Page 17: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

diberikan ke referensi menggunakan operator baru. For example, we can write Sebagai contoh, kita dapat menulis

double x[]; // create an array reference x = new double[5]; // create array object double x []; / / membuat sebuah array acuan x = new double [5]; / / buat objek array

Or we can create an array reference and an array object on a single line: Atau kita dapat menciptakan sebuah array referensi dan sebuah array objek pada satu baris: double x[] = new double[5]; double x [] = new double [5];

The number of elements in the array x is x.length . Jumlah elemen dalam array x adalah x.length. The elements of the array are written as x[0], x[1], x[2], x[3], x[4] . Elemen-elemen dari array ditulis sebagai x [0], x [1], x [2], x [3], x [4].

An array object may be created and initialized when its reference is declared. Objek array dapat dibuat dan diinisialisasi ketika referensi diumumkan. For example, Misalnya

double x[] = {1.0, 1.4, 1.6, 1.8, 3.0}; double x [] = (1.0, 1.4, 1.6, 1.8, 3,0);

It is a good idea to declare array sizes using named constants (final variables) so that the length of the arrays can be easily changed. Ini adalah ide yang baik untuk menyatakan ukuran array menggunakan nama konstanta (variabel terakhir) sehingga panjang array dapat dengan mudah berubah. final int ARRAY_SIZE = 1000; double x[] = new double[ARRAY_SIZE]; int akhir ARRAY_SIZE = 1000; double x [] = new double [ARRAY_SIZE];

Two-dimensional arrays Array dua dimensi A two-dimensional array is implemented by creating a one-dimensional array each of whose elements is also an array. Sebuah array dua dimensi ini diterapkan dengan membuat array satu dimensi yang masing-masing elemen juga merupakan array. We first declare a reference to an array of arrays and then create the individual arrays associated with each element. Kami pertama-tama menyatakan referensi ke array dari array dan kemudian membuat array individu yang terkait dengan setiap elemen. For example Misalnya double x[][]; / create reference to an array of arrays double x [][]; / membuat referensi ke array dari array

Then we can write for example, Kemudian kita bisa menulis misalnya, x = new double[3][5]; create array objects x = new double [3] [5]; membuat obyek array

Methods and Scope Metode dan Ruang Lingkup

The general form of a method definition is Bentuk umum definisi suatu metode

Page 18: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

return-value-type method-name(parameter list) { declarations and statements (return statement) } pengembalian nilai metode-tipe nama (daftar parameter) (deklarasi dan pernyataan (pernyataan kembali)) The return-value-type is the data type of the result returned by the method to

the caller. Kembalinya-nilai jenis tipe data hasil dengan metode kembali ke pemanggil. If no value is returned, the return-value-type is void . Jika belum ada nilai yang dikembalikan, kembalinya nilai tipe void. If the return-value-type is not void, then there must be a return statement. Jika nilai pengembalian jenis tidak batal, maka harus ada pernyataan kembali.

The parameter-list is a comma-separated list containing the parameters received by the method whenever it is called. Parameter-list adalah sebuah daftar dipisahkan koma berisi parameter yang diterima oleh metode setiap kali disebut. A type must be declared for every parameter in the list. Suatu jenis harus dinyatakan untuk setiap parameter dalam daftar. If the parameter-list is empty, the parentheses is still required. Jika daftar parameter kosong, tanda kurung masih diperlukan.

Variables that are used within a method and that are not accessible by calling methods are local variables . Variabel yang digunakan dalam metode dan yang tidak dapat diakses dengan memanggil metode variabel lokal.

Java programs communicate with their methods using pass-by-value. The method works with a copy of the original argument, not the argument itself which means that the method cannot modify the original argument even if it modifies the parameter. Program java berkomunikasi dengan metode mereka menggunakan pass-by-nilai. Metode yang bekerja dengan salinan asli argumen, bukan argumen itu sendiri yang berarti bahwa metode ini tidak dapat memodifikasi argumen asli meskipun memodifikasi parameter. A program that illustrates pass-by-value os shown below. Suatu program yang menggambarkan pass-by-nilai os ditunjukkan di bawah ini.

public class TestPassByValue { public static void main(String[] args) { // instantiate a TestPassByValue object TestPassByValue t = new TestPassByValue(); int i = 1; // local variable System.out.println("value of i before test = " + i); // pass value of local variable int j = t.test(i); System.out.println("value of i after test = " + i); System.out.println("value of j = " + j); j = t.test2(j); System.out.println("value of i after test2 = " + i); System.out.println("value of j after test2 = " + j); } public int test (int i) { i = ++i; // same as i = i + 1; System.out.println("value of i in test = " + i); return i; } public int test2 (int k) { int i = k; // i refers to instance variable

Page 19: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

System.out.println("value of k = " + k); i = ++i; System.out.println("value of i in test2 = " + i); return i; } } public class TestPassByValue (public static void main (String [] args) (/ / instantiate a TestPassByValue objek TestPassByValue t = new TestPassByValue (); int i = 1; / / variabel lokal System.out.println ( "nilai i sebelum ujian = "+ i); / / lulus nilai variabel lokal int j = t.test (i); System.out.println (" nilai i setelah tes = "+ i); System.out.println (" nilai j = "+ j); j = t.test2 (j); System.out.println (" nilai i setelah test2 = "+ i); System.out.println (" nilai j setelah test2 = "+ j );) public int test (int i) (i = + + i; / / sama seperti i = i + 1; System.out.println ( "nilai i di tes =" + i); return i;) public int test2 (int k) (int i = k; / / i mengacu pada contoh variabel System.out.println ( "Nilai k =" + k); i = + + i; System.out.println ( "nilai i di test2 = "+ i); return i;))

Variables have either class scope or block scope . Variabel-variabel kelas baik lingkup atau cakupan blok. Methods and the instance variables of a class have class scope. Metode dan variabel contoh dari sebuah kelas memiliki cakupan kelas. Class scope begins at the opening left brace and ends at the closing right brace of the class definition. Kelas lingkup dimulai pada pembukaan penyangga kiri dan berakhir pada penutupan penjepit kanan dari definisi kelas. Class scope allows any method in the class to directly invoke any other method in the class and to directly access any instance variable of the class. Kelas lingkup memungkinkan metode apapun di kelas untuk secara langsung memanggil metode lain di dalam kelas dan untuk secara langsung mengakses variabel instance kelas. In effect, instance variables are global variables within a class. Akibatnya, misalnya variabel variabel global dalam kelas. Instance variables can be used to communicate between methods in a class or to retain information between calls of a given method in the class. Misalnya variabel dapat digunakan untuk berkomunikasi antara metode di kelas atau untuk mempertahankan informasi antara panggilan dari sebuah metode yang diberikan di kelas.

A block is a compound statement and consists of all the statements between an opening and closing brace. Satu blok adalah pernyataan majemuk dan terdiri dari semua pernyataan antara pembuka dan penutup penjepit. Variables defined inside a block have block scope. Variabel didefinisikan di dalam sebuah blok memiliki cakupan blok. Variables defined within a block have block scope and are visible within the block; they are not visible outside the block. Variabel didefinisikan dalam blok blok memiliki cakupan dan terlihat dalam blok, mereka tidak terlihat di luar blok.

A variable can have the same name as an instance variable as an instance variable or method in the class in which the method is defined. Sebuah variabel dapat memiliki nama yang sama sebagai contoh variabel sebagai contoh variabel atau metode dalam

Page 20: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

kelas di mana metode didefinisikan. In this case the instance variable is hidden from the method by the local variable. Dalam hal ini contoh variabel tersembunyi dari metode variabel lokal. Example: Contoh:

public class Point { // define instance data public double x,y; // instance variables // define constructors public Point() { x = 1; // same variables as instance variables y = 1; } public Point (double x, double y) { this.x = x; // this.x refers to instance variable this.y = y; this.x++; System.out.println("this.x = " + this.x); System.out.println("x = " + x); // parameter variable } public Point (double x, double y, boolean dummy) { x++; System.out.println("x = " + x); } } public class TestPoint { public static void main(String[] args) { /* Need an instance of class Particle - a particle object; assign it to the variable a which is of type Particle. public class Point (/ / define data contoh public double x, y; / / instance variable / / define konstruktor public Point () (x = 1; / / variabel yang sama seperti contoh variabel y = 1;) public Point (double x, double y) (this.x = x; / / this.x mengacu pada variabel contoh this.y = y; this.x + +; System.out.println ( "this.x =" + this.x); System.out . println ( "x =" + x); / / parameter variabel) public Point (double x, double y, boolean dummy) (x + +; System.out.println ( "x =" + x);)) public class TestPoint (public static void main (String [] args) (/ * Perlu sebuah instance dari kelas partikel - partikel objek; assign ke suatu variabel yang bertipe Particle. */ Point a = new Point(2.0,1.0); System.out.println("x = " + ax); Point b = new Point(); bx = 3.0; System.out.println("xb = " + bx); } } * / Point a = new Point (2.0,1.0); System.out.println ( "x =" + ax); Huruf b = new Point (); bx = 3.0; System.out.println ( "xb =" + bx);))

Simple Graphics Sederhana Graphics

A powerful feature of Java is its ability to do graphics relatively simply. Sebuah fitur kuat Jawa adalah kemampuannya untuk melakukan grafis yang relatif sederhana. We next introduce several methods in the Particle class to draw a representation of

Page 21: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

the particle. Selanjutnya kami memperkenalkan beberapa metode dalam kelas partikel untuk menggambar sebuah representasi dari partikel. import java.awt.*; public class Particle { double x,y; Color color; // part of AWT package public Particle(double x, double y) { // constructor with color variable this.x = x; this.y = y; color = Color.blue; // define default color } // Draw representation of particle in given graphics context public void draw(Graphics g) { Color oldColor = g.getColor(); g.setColor(color); g.fillOval((int)x, (int)y, 12, 12); g.setColor(oldColor); } public Color getColor() { return color; } public void setColor(Color newColor) { color = newColor; } public void move(double dx, double dy) { x += dx; // same as x = x + dx; y += dy; } } import java.awt .*; public class Particle (double x, y; Color warna; / / bagian dari paket AWT Particle publik (double x, double y) (/ / constructor dengan variabel warna this.x = x; this.y = y; color = Color.blue; / / define default color) / / menggambar representasi grafis partikel dalam konteks tertentu public void draw (Graphics g) (Warna oldColor = g.getColor (); g.setColor (warna); g . fillOval ((int) x, (int) y, 12, 12); g.setColor (oldColor);) public Color getColor () (return color;) public void setColor (Warna newColor) (color = newColor;) public void pindah (double dx, double dy) (x + = dx; / / sama dengan x = x + dx; y + = dy;)) The import statement allows us to use the Java libraries. Pernyataan impor

memungkinkan kita untuk menggunakan Java perpustakaan. The notation java.awt.* means that all the classes in the java.awt package can be used. Notasi java.awt .* berarti bahwa semua kelas dalam paket java.awt dapat digunakan. This package implements the Java Abstract Window Toolkit (AWT) and contains all the classes and interfaces necessary for creating a user interface. Paket ini mengimplementasikan Java Abstract Window Toolkit (AWT) dan berisi semua kelas dan interface yang diperlukan untuk menciptakan user interface. Packages are a way of grouping a collection of related classes. Paket adalah cara pengelompokan koleksi kelas terkait. A description of all the packages is given at the Sun Web site . Sebuah penjelasan dari semua paket yang diberikan di situs Web Sun.

We have used the java.awt.Graphics class which provides drawing and painting methods. Kami telah menggunakan java.awt.Graphics kelas yang menyediakan metode menggambar dan melukis. The method draw has an argument g of type Graphics . Metode menarik memiliki

Page 22: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

tipe argumen g Graphics. Think of g as a part of the screen (a bit map) where painting will take place and the methods that are associated with it. Pikirkan g sebagai bagian dari layar (sedikit peta) di mana lukisan akan berlangsung dan metode-metode yang berkaitan dengan itu.

The four principal elements need to create a GUI include: Keempat unsur utama perlu menciptakan GUI meliputi:

1. Components. Komponen. A component is a visual object containing text or graphics that can respond to keyboard or mouse inputs. Komponen adalah objek visual yang berisi teks atau grafis yang dapat merespon input keyboard atau mouse. Examples of components include buttons, labels, text boxes, check boxes, and lists. Contoh komponen termasuk tombol, label, kotak teks, kotak cek, dan daftar. A blank component is known as a canvas , which can be used as a drawing area for text or graphics. Komponen kosong dikenal sebagai kanvas, yang dapat digunakan sebagai area gambar teks atau grafis. All components inherit a common set of methods, the most common of which is paint . Semua komponen mewarisi seperangkat metode, yang paling umum yang cat.

2. A container is a graphical object that can hold components or other containers. Sebuah wadah adalah objek grafis yang dapat memegang komponen atau wadah lainnya. The most important type of container is a Frame . Jenis yang paling penting adalah wadah Frame.

3. Layout Manager . Layout Manager. A layout manager is automatically associated with each container when it is created, but the layout manager can be changed. Seorang manajer layout secara otomatis terkait dengan setiap wadah ketika dibuat, tetapi manajer tata letak dapat diubah. Examples include BorderLayout, BoxLayout, GridLayout. Contohnya termasuk BorderLayout, BoxLayout, GridLayout.

4. Event Handlers . Event Handler. Events, such as the click of a mouse, are handled by creating listener classes which implement listener interfaces . Peristiwa, seperti klik pada mouse, ditangani oleh pendengar menciptakan kelas-kelas yang mengimplementasikan antarmuka pendengar. The standard listener interfaces are in java.awt.event . Pendengar standar antarmuka dalam java.awt.event.

The following simple class draws the particle: Kelas sederhana berikut menarik partikel: import java.awt.*; public class ParticleDrawer extends Frame { public static void main(String[] args) { // Create new frame ParticleDrawer frame = new ParticleDrawer(); } // Construct ParticleDrawer frame public ParticleDrawer() { // predefined methods setSize(512, 342); // units of coordinate system in pixels setVisible(true); } // Paint particles public void paint(Graphics g) { Particle p = new Particle(3.1, 4.1);

Page 23: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

p.draw(g); p.move(26.5, 35.8); p.setColor(Color.red); p.draw(g); } } import java.awt .*; ParticleDrawer public class extends Frame (public static void main (String [] args) (/ / Buat ParticleDrawer bingkai baru bingkai = new ParticleDrawer ();) / / Bina ParticleDrawer publik ParticleDrawer bingkai () (/ / metode standar setSize (512, 342); / / unit sistem koordinat dalam pixel setVisible (true);) / / public void partikel cat cat (Graphics g) (p = partikel partikel baru (3.1, 4.1); p.draw ( g); p.move (26,5, 35,8); p.setColor (Color.red); p.draw (g);)) A frame is a very simple window, with a border, a place for a title, and a

close window button. Sebuah frame jendela yang sangat sederhana, dengan perbatasan, sebuah tempat untuk judul, dan tombol jendela dekat.

Note how the { paint method is used. Perhatikan bagaimana (cat metode yang digunakan. It is not called directly. Hal ini tidak disebut secara langsung. Instead, whenever the frame is shown, the paint method is called. Sebaliknya, setiap kali frame ditampilkan, metode cat disebut. In addition, if one covers the frame with another window, the paint method will be called again when the frame is uncovered. Selain itu, jika satu mencakup bingkai dengan jendela yang lain, metode cat akan dipanggil lagi ketika frame terungkap. To directly call the paint method, use the repaint() method. Untuk langsung memanggil metode cat, gunakan repaint () method.

As an example we draw the trajectory of a projectile. Sebagai contoh, kita menggambar lintasan sebuah peluru. To do so we add to Particle the method step to integrate the equations of motion for one time step. Untuk melakukannya kita menambahkan metode Particle langkah untuk mengintegrasikan persamaan gerak untuk satu kali langkah. The arguments of step are the time step and the Force on the particle, which is defined in another class. Argumen langkah adalah langkah waktu dan Angkatan pada partikel, yang didefinisikan dalam kelas lain. We also add other useful methods. Kami juga menambahkan metode lain yang bermanfaat. public class Particle { private double x,y,vx,vy,ax,ay; private double mass = 1.0; private boolean firststep = true; public Particle(double x, double y, double vx, double vy) { this.x = x; this.y = y; this.vx = vx; this.vy = vy; } public double getMass() { return mass; } public void setMass(double mass) { this.mass = mass; } public double getX() { return x; } public double getY() { return y; } public double getVx() { return vx; } public double getVy()

Page 24: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

{ return vy; } public double getAx() { return ax; } public double getAy() { return ay; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public void setVx(double vx) { this.vx = vx; } public void setVy(double vy) { this.vy = vy; } public void step(double dt, Force f) { if (firststep) { ax = f.getfx(x,y,vx,vy,this)/mass; // acceleration at beginning of interval ay = f.getfy(x,y,vx,vy,this)/mass; firststep = false; } // Euler-Richardson algorithm double vxm = vx + 0.5*ax*dt; // velocity at middle of interval double vym = vy + 0.5*ay*dt; double xm = x + 0.5*vx*dt; // position at middle of interval double ym = y + 0.5*vy*dt; double axm = f.getfx(xm,ym,vxm,vym,this)/mass; double aym = f.getfy(xm,ym,vxm,vym,this)/mass; vx += axm*dt; // velocity at end of interval vy += aym*dt; x += vxm*dt; // position at end of interval y += vym*dt; ax = f.getfx(x,y,vx,vy,this)/mass; // acceleration at end of interval ay = f.getfy(x,y,vx,vy,this)/mass; } } public class Force { private final static double g = 9.8; // not convention double b = 0; // used in drag force public void setb(double b) { this.b = b; } public double getfx(double x, double y, double vx, double vy, Particle p) { return -b*vx; } public double getfy(double x, double y, double vx, double vy, Particle p) { return -b*vy - g*p.getMass(); } } public class Particle (private double x, y, vx, vv, ax, ay; private double massa = 1,0; private boolean firststep = true; Particle publik (double x, double y, double vx, double vy) (this.x = x; this.y = y; this.vx = vx; this.vy = vy;) public double getMass () (return massa;) public void setMass (double massa) (this.mass = massa;) public double getX ( ) (return x;) public double getY () (return y;) public double getVx () (return vx;) public double getVy () (return vy;) public double getAx () (return ax;) public double getAy ( ) { return ay; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; }

Page 25: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

public void setVx(double vx) { this.vx = vx; } public void setVy(double vy) { this.vy = vy; } public void step(double dt, Force f) { if (firststep) { ax = f.getfx(x,y,vx,vy,this)/mass ; // acceleration at beginning of interval ay = f.getfy(x,y,vx,vy,this)/mass; firststep = false; } // Euler-Richardson algorithm double vxm = vx + 0.5*ax*dt; / / velocity at middle of interval double vym = vy + 0.5*ay*dt; double xm = x + 0.5*vx*dt; // position at middle of interval double ym = y + 0.5*vy*dt; double axm = f .getfx(xm,ym,vxm,vym,this)/mass; double aym = f.getfy(xm,ym,vxm,vym,this)/mass; vx += axm*dt; // velocity at end of interval vy += aym*dt; x += vxm*dt; // position at end of interval y += vym*dt; ax = f.getfx(x,y,vx,vy,this)/mass; // acceleration at end of interval ay = f.getfy(x,y,vx,vy,this)/mass; } } public class Force { private final static double g = 9.8; // not convention double b = 0; // used in drag force public void setb(double b) { this.b = b; } public double getfx(double x, double y, double vx, double vy, Particle p) { return -b*vx; } public double getfy(double x , double y, double vx, double vy, Particle p) { return -b*vy - g*p.getMass(); } }

Note that {\tt If} statements are the same as in C/C++ except that Java uses a boolean value to condition the execution. Summary of relational operators .

The step method implements the Euler-Richardson integration algorithm. We need to compute the acceleration at the beginning of the interval the first time the algorithm is used. Then we can use the acceleration computed at the end of the previous interval. Note how this is used in the step method to refer to the Particle itself; in Force we use the argument Particle to get the particle's mass.

The class that draws the trajectory is given below.

import java.awt.*; public class Simulation extends Frame { public static void main(String[] args) { Simulation sim = new Simulation(); // set up window for application } public Simulation() { setSize(512,342); setVisible(true); } } public void

Page 26: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

paint(Graphics g) { setBackground(Color.white); calculateTrajectory(g); } private void calculateTrajectory(Graphics g) { final double tmax = 10.0; final double dt = 0.5; Particle p = new Particle(0.0, 200.0, 40.0, 25.0); Force f = new Force(); g.setColor(Color.blue); double time = 0.0; while (time < tmax) { // draw circle of diameter 10 pixels. note use of casting g.drawOval((int)p.getX(), getSize().height - (int)p.getY(), 10, 10); p.step(dt,f); time += dt; } } } The Simulation class extends the Frame class. The paint method is

called when the Frame is first shown and anytime Frame is brought to the front.

Java uses a coordinate system whose origin is at the upper left-hand corner with positive x values to the right and positive y values down. Because of this choice of screen coordinate system, we need to convert world coordinates to screen coordinates when drawing an oval to represent the particle. Because the last two arguments of drawOval are the same, the oval is a circle. (Note that drawOval requires integers.)

Note the use of the while statement which allows all the statements within the braces of the while statement to be executed again and again as long as the argument of the while statement (time < tmax) is true.

An alternative to the while loop is the for loop which looks like

for (int i = 0; i < 10; i++) statement;

or atau

for (int i = 0; i < 10; i++) { statement 1; ... statement n; }

Semicolons are used to separate the fields inside the parenthesis. The first field initializes a variable. Usually, the variable is also declared here. The second field determines under what condition the loop will continue. The third field lists how the variable in the first field changes at the end of each pass through the loop. More information about loops .

Offscreen buffers

When the window of another application covers the frame, Java automatically calls paint when the user returns to our original program. This action allows us to see the contents of the original window. However, in the above program it means that the trajectory must be recomputed. A better approach is to first draw the trajectory to an offscreen image buffer and then blast the latter to the screen. As long as the buffer is saved, no new calculations need to be done.

Page 27: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

First we will show how this is done for the Simulation class and then we will show an example where it is more useful. // Image and Graphics do not use constructors.

import java.awt.*; public class Simulation extends Frame { Image offscreen; // make image class variable so available to all methods public static void main(String[] args) { Simulation sim = new Simulation(); // set up window for application } public Simulation() { setSize(512, 342); setVisible(true); offscreen = createImage(getSize().width, getSize().height); calculateTrajectory(); } public void paint(Graphics g) { setBackground(Color.white); g.drawImage(offscreen, 0, 0, this); // draw image onto screen } public void calculateTrajectory() { final double tmax = 10.0; final double dt = 0.5; Graphics g = offscreen.getGraphics(); g.setColor(Color.blue); Particle p = new Particle(0.0, 200.0, 40.0, 25.0); Force f = new Force(); double time = 0.0; while (time < tmax) { g.drawOval((int)p.getX(), getSize().height - (int)p.getY(), 10, 10); p.step(dt,f); time += dt; } } } The Graphics class is used here to provide drawing methods for offscreen

, which is an instantiation of the Image class. Both Graphics and Image cannot be instantiated directly with a constructor, instead we can use the getGraphics and createImage methods, respectively. The Image class represents a displayable image.

Note how we declare offscreen outside of any method, and instantiate it with the createImage method in the constructor. This is a common technique for making objects accessible to all the methods of a class, and to insure that they continue to exist after a method returns.

User Interaction

Offscreen buffers are useful when we want to draw more than one trajectory without running the program over again. To do so we want the user to interact with the program. This feature is very easy to accomplish using components such as Buttons, TextFields, and Menus. Below we show how to use a TextField to receive a number from the user. We put the TextField on a separate frame and use an actionListener to detect whether the user has entered a number in the TextField. The number entered will be the friction coefficient, b, used in a drag force of the form -bv .

Page 28: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

import java.awt.*; import java.awt.event.*; // needed for actionListener class ParameterInput extends Frame { TextField tf; Label lb; Simulation sim; public FrictionInput (Simulation sim) // pass address of object { this.sim = sim; setUpFrame(); } public void setUpFrame() { setTitle("Friction Input"); setSize(200,100); setLocation(400,50); // location for frame setLayout(null); // not using any layout manager lb = new Label("Friction Coefficient"); // new label for textfield lb.setSize(150,20); lb.setLocation(30,70); add(lb); // add label tf = new TextField(); // new textfield tf.addActionListener(new actionTF()); // add listener tf.setSize(50,20); tf.setLocation(30,40); add(tf); // add textfield setVisible(true); } class actionTF implements ActionListener // example of Internal class // user has to tell ActionLister what to do so have to implement it. { public void actionPerformed(ActionEvent e) { Double R = new Double(tf.getText().trim()); // convert text to number // trim gets rid of extra zeros sim.calculateTrajectory(R.doubleValue()); } } } There are two objects attached to the Frame. Label lb represents some

text that will be placed under the TextField tf . The size and location of each of these components is specified. There are layout managers that automatically decide these specifications for you, but they frequently do not look good.

One of the features of Java is the use of the actionListener which is implemented by using the addActionListener method and an internal class which implements the ActionListener interface . An interface is like a class except none of the methods have implementations. Instead the user must supply these as we have done above for the method actionPerformed(ActionEvent e) . The beauty of the above event model is that the user does not have to write code to check for an occurence of an event in other parts of the program. Whenever, a number is entered into the TextField, the actionPerformed method will be executed. Here we extract the number by converting the string in the TextField to a number using the Double class, and then call the calculateTrajectory method of the object sim .

Page 29: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

The following modification of Simulation uses FrictionInput .

import java.awt.*; public class Simulation extends Frame { private Image offscreen; private int counter = 0; // used to change color for each trajecto public static void main(String[] args) { Simulation sim = new Simulation(); // set up window for application FrictionInput fi = new FrictionInput(sim); // set up second window } public Simulation() // constructor { setSize(512, 342); setVisible(true); offscreen = createImage(getSize().width, getSize().height); } public void paint(Graphics g) { setBackground(Color.white); g.drawImage(offscreen, 0, 0, this); // draw image on screen } public void calculateTrajectory(double b) { final double tmax = 10.0; final double dt = 0.5; Graphics g = offscreen.getGraphics(); // create buffer changeColor(g); Particle p = new Particle(0.0, 200.0, 40.0, 25.0); Force f = new Force(); f.setb(b); double time = 0.0; while (time < tmax) { g.drawOval((int)p.getX(), getSize().height - (int)p.getY(), 10, 10); p.step(dt,f); time += dt; } repaint(); } public void changeColor(Graphics g) { switch(counter++) { case 0: g.setColor(Color.red); break; case 1: g.setColor(Color.blue); break; case 2: g.setColor(Color.green); break; case 3: g.setColor(Color.yellow); break; case 4: g.setColor(Color.magenta); break; case 5: g.setColor(Color.orange); break; case 6: g.setColor(Color.cyan); break; case 7: g.setColor(Color.pink); break; default: g.setColor(Color.black); } } } Note the use of the method repaint which clears the Frame and calls

paint . However, all the trajectories are still on on the offscreen buffer so that they will all appear on the screen.

Page 30: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

We have added a method, changeColor , which uses a different color each time a new trajectory is drawn, up to 8 trajectories. Any more trajectories are colored black. Note the use of the switch statement. Each time a trajectory is drawn, the value of counter is checked and then incremented (using counter++ . (Note that counter++; means that the current value of counter is used in the switch statement before it is incremented by 1. If we used ++counter; instead, counter would be incremented by 1 first.) The value checked then determines which statement to execute. Also note the use of the break statement. Without it every case would be executed.

The switch statement is useful if there are many possible choices. If there are only a few choices or if the choices cannot be encoded as an integer, then the if statement can be used. Examples of the latter are as follows:

if (x < 0) { y = 20; x = 10; } if (x < 0) y = 10; // braces not needed for single statement else y = 20; if (x < 0) y = 10; else if (x > 0) y = 20; else y = 30;

Animation Animasi

We now return to a single trajectory and discuss animation. Instead of showing the trajectory we will simply show a ball as it moves. The following code does this so that there is very little flicker. We have reduced the time step so that the motion of the ball will be slowed down.

import java.awt.*; public class Simulation extends Frame { Image offscreen; public static void main(String[] args) { Simulation sim = new Simulation(); // set up window for application sim.calculateTrajectory(); } public Simulation() { // constructor setSize(512, 342); setVisible(true); offscreen = createImage(getSize().width, getSize().height); } public void paint(Graphics g) { setBackground(Color.white); g.drawImage(offscreen,0,0,this); } public void calculateTrajectory() { final double tmax = 10.0; final double dt = 0.005; Graphics b = offscreen.getGraphics(); Particle p = new Particle(0.0, 200.0, 40.0, 25.0); Force f = new Force(); double time = 0.0; while (time < tmax) { Rectangle oldRect = new Rectangle((int)p.getX(),getSize().height -(int)p.getY(),11,11); p.step(dt,f);

Page 31: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

time += dt; Rectangle newRect = new Rectangle((int)p.getX(),getSize().height -(int)p.getY(),11,11); // new region of ball Rectangle r = newRect.union(oldRect); // new plus old region // b is buffer. key to avoid flicker is not to call repaint b.clearRect(rx,ry,r.width,r.height); // clear new plus old region on buffer b.fillOval((int)p.getX(), getSize().height - (int)p.getY(), 10, 10); Graphics g = getGraphics(); g.drawImage(offscreen,0,0,this); } } }

The basic strategy used above is to define three rectangles. One containing the old position of the ball, one containing the new position, and one which is the union of the two. Then we clear the buffer of this latter rectangle, and draw our new ball. We then draw our image to the screen. Note how we grab the Graphics object for the screen within calculateTrajectory instead of using repaint . This avoids some of the flickering that would occur from clearing the Frame.

Threads Threads

Often we want the user to be able to interrupt a simulation while it is running, and then start it going again. For example, we might want to know the coordinates of our ball at some instant while we are watching it. One can use Threads to accomplish this. Basically, a Thread is a process which is running parallel to another process. Below we set up a Thread and use a MouseListener to interrupt the program. The interface Runnable contains the methods we need to start, stop, and run the Thread. import java.awt.*; import java.awt.event.*; public class Simulation extends Frame implements MouseListener, Runnable { Image offscreen; Graphics gb; // graphics buffer Particle p; Force f; boolean running = false; Thread runner; public static void main(String[] args) { Simulation sim = new Simulation(); // set up window for application } public Simulation() { // constructor setSize(512, 342); setVisible(true); offscreen = createImage(getSize().width, getSize().height); p = new Particle(0.0, 200.0, 40.0, 25.0); f = new Force(); gb = offscreen.getGraphics(); start(); // method associated with thread addMouseListener(this); // this refer to frame class } public void paint(Graphics g) { setBackground(Color.white); g.drawImage(offscreen,0,0,this); } public void start() { runner = new Thread(this);

Page 32: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

// this refers to frame runner.start(); } public void stop() { runner.stop(); } public void run() { while(true) { try {Thread.sleep(5);} // delay 5 msec between updates catch (InterruptedException e){}; // would catch the moue click if(running) calculateTrajectory(); } } public void mouseClicked(MouseEvent e) { // see coordinates Graphics g = getGraphics(); g.clearRect(0,0,getSize().width, getSize().height); g.fillOval((int)p.getX(), getSize().height - (int)p.getY(), 10, 10); g.drawString("x = " + String.valueOf(p.getX()),e.getX(),e.getY()); g.drawString("y = " + String.valueOf(p.getY()),e.getX(),e.getY() + 30); running = false; } public void mouseEntered(MouseEvent e) {running = true;} // move inside frame, runs; otherwise stops public void mouseExited(MouseEvent e) {running = false;} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void calculateTrajectory() { // should be draw trajectory private final double dt = 0.005; Rectangle oldRect = new Rectangle((int)p.getX(),getSize().height -(int)p.getY(),11,11); p.step(dt, f); time += dt; Rectangle newRect = new Rectangle((int)p.getX(),getSize().height -(int)p.getY(),11,11); Rectangle r = newRect.union(oldRect); gb.clearRect(rx,ry,r.width,r.height); gb.fillOval((int)p.getX(), getSize().height - (int)p.getY(), 10, 10); Graphics g = getGraphics(); g.drawImage(offscreen,0,0,this); } }

We have modified calculateTrajectory so that it only computes and draws one step. We have eliminated the while statement. Instead control of the trajectory is given to the run method of the Thread runner . The try catch statement is used to interrupt the Thread for 5 milliseconds to check to see if any event occurred. The MouseListener checks for events. In this case we can stop the motion by moving the mouse outside the Frame, and start it again by moving it into the Frame and start it again by moving it into the Frame. If the mouse is clicked, we write the x and y coordinates of the ball at the locatiuon of the mouse click, redraw the ball, and stop the motion. Note that the interface methods mousePressed and mouseReleased must be defined even though they do not do anything in this example.

Page 33: Introduction to Java Pengenalan Javafitria_okta.staff.gunadarma.ac.id/Downloads/files/37708/... · Web viewJava is an object-oriented programming language with a built-in application

References Referensi

1. Stephen J. Chapman, Java for Engineers and Scientists , Prentice-Hall (2000). 2. Bruce Eckel, Thinking in Java , Prentice-Hall (1998). Covers all the syntax,

plus some finer points of OOP. 3. Matthias Felleisen and Daniel Friedman, A Little Java, A Few Patterns, MIT

Press (1998). Cute little tutorial that does not teach much syntax, but is designed to improve your OOP style.

4. David Flanagan, Java in a Nutshell, second edition, O'Reilly (1997). 5. David Geary, Graphic Java, Addison-Wesley. 6. Joseph O'Neil and Herb Schildt, Teach Yourself Java, Osborne (1999). Good

language reference for getting up to speed quickly. 7. Walter Savitch, Java: An introduction to Computer Science and Programming

, Prentice-Hall (1999). 8. Sun's Java Documentation or better JavaDoc2 . 9. Patrick Winston and Sundar Narasimhan, On to Java, 2nd ed., Addison-

Wesley (1999). 10. Also see javaintro and Java development tutorial . 11. Peter van der Linden, Just Java and Beyond, Sun Microsystems. 12. Patrick Chan and Rosanna Lee, The Java Developers Almanac 2000.

Please send comments and corrections to Jan Tobochnik, [email protected] or Harvey Gould, [email protected] .

Updated 20 July 2000.

LINK: http://translate.google.co.id/translate?hl=id&langpair=en|id&u=http://sip.clarku.edu/tutorials/java/java.html

http://translate.google.co.id/translate?hl=id&langpair=en|id&u=http://math.hws.edu/javanotes/

http://bebas.vlsm.org/v06/Kuliah/SistemOperasi/BUKU/SistemOperasi-4.X-1/ch04.html