The Preprocessor
All C/C++ compilers implement a stage of compilation known as the preprocessor. Semua C / C + + compilers melaksanakan tahap kompilasi dikenal sebagai preprocessor. The C++ preprocessor basically performs an intelligent search and replace on identifiers that have been declared using the #define directive or typedef . C + + preprocessor pada dasarnya melakukan pencarian cerdas dan penggantian pada pengenal yang telah dideklarasikan menggunakan direktif # define atau typedef. Although most advocators of C++ discourage the use of the preprocessor, which was inherited from C, it is still widely used by most C++ programmers. Meskipun kebanyakan advocators C + + menghambat penggunaan preprocessor, yang diwariskan dari C, masih banyak digunakan oleh sebagian besar + C + programmer. Most of the processor definitions in C++ are stored in header files, which complement the actual source code (implementation) files. Sebagian besar definisi prosesor di C + + disimpan dalam file header, yang melengkapi kode sumber aktual (implementasi) file.The problem with the preprocessor approach is that it provides an easy way for programmers inadvertently to add unnecessary complexity to a program. Masalah dengan pendekatan preprosesor adalah bahwa ia menyediakan cara mudah bagi programmer sengaja untuk menambahkan kompleksitas yang tidak perlu ke program. Many programmers using #define and typedef end up inventing their own sublanguage within the confines of a particular project. Banyak programmer menggunakan # define dan berakhir typedef Facebook menciptakan sub-bahasa mereka sendiri dalam batas-batas dari suatu proyek tertentu. This results in other programmers having to go through the header files and sort out all the #define and typedef information to understand a program, which makes code maintenance and reuse almost impossible. Hal ini mengakibatkan programmer lain harus melalui file-file header dan memilah semua # define dan informasi typedef untuk memahami sebuah program, yang membuat pemeliharaan dan penggunaan kembali kode hampir mustahil. An additional problem with the preprocessor approach is that it is very weak when it comes to type checking and validation. Masalah tambahan dengan pendekatan preprosesor adalah bahwa hal itu sangat lemah ketika datang untuk memeriksa jenis dan validasi.
Java does not have a preprocessor. Java tidak memiliki preprocessor satu. It provides similar functionality ( #define , typedef , and so forth) to that provided by the C++ preprocessor, but with far more control. Ini menyediakan fungsionalitas yang sama (# define, typedef, dan sebagainya) untuk yang disediakan oleh C + + preprocessor, tetapi dengan kontrol lebih jauh. Constant data members are used in place of the #define directive, and class definitions are used in lieu of typedef . Konstan data anggota digunakan di tempat yang # define direktif, dan definisi kelas digunakan sebagai pengganti typedef. The end result is that Java source code is much more consistent and easier to read than C++ source code. Hasil akhirnya adalah bahwa kode sumber Java jauh lebih konsisten dan lebih mudah untuk dibaca daripada kode sumber C + +. Additionally, as you learned earlier, Java programs don't use header files; the Java compiler builds class declarations directly from the source code files, which contain both class declarations and method implementations. Selain itu, seperti yang Anda pelajari sebelumnya, program Java tidak menggunakan file header, compiler Java membangun deklarasi kelas langsung dari file kode sumber, yang mengandung baik deklarasi kelas dan metode implementasi.
Let's look at an example; Listing 28.1 shows a C++ header file for a ball class. Mari kita lihat contoh; properti 28,1 menunjukkan C + + file header untuk kelas bola.
Listing 28.1. Listing 28.1. The C++ ball class. C + + kelas bola.
#define COLOR_RED 1 # Define COLOR_RED 1
#define COLOR_YELLOW 2 # Define COLOR_YELLOW 2
#define COLOR_BLUE 3 # Define COLOR_BLUE 3
#define MATERIAL_RUBBER 1 # Define MATERIAL_RUBBER 1
#define MATERIAL_LEATHER 2 # Define MATERIAL_LEATHER 2
class ball { class bola {
float diameter; float diameter;
int color; int warna;
int material; int bahan;
}; };
To move this code to Java, the only change is to get rid of the preprocessor #define directives and the semicolon at the end of the class declaration. Untuk memindahkan kode ini ke Jawa, perubahan hanya untuk menyingkirkan preprocessor # define arahan dan titik koma di akhir deklarasi kelas. You get rid of the #define directives by declaring Java class members that are static and final . Anda bisa sembuh dari # define arahan dengan menyatakan anggota kelas Java yang statis dan final. For data members in Java, the static keyword means there is only one copy for the entire class, and the final keyword means that they are constant, which is usually the motive for using #define in C/C++ code. Untuk anggota data di Jawa, kata kunci statis berarti hanya ada satu salinan untuk seluruh kelas, dan kata kunci final berarti bahwa mereka adalah konstan, yang biasanya merupakan motif untuk menggunakan # define dalam C C + + kode /. Listing 28.2 shows the resulting Java version of this class. Listing 28.2 menunjukkan versi Java yang dihasilkan dari kelas ini. Keep in mind that the Java version is not stored in a header file, because Java doesn't support header files; in Java, definitions and declarations are combined in one place, the .java source file. Perlu diketahui bahwa versi Jawa tidak disimpan dalam file header, karena Java tidak mendukung file header, di Jawa, definisi dan deklarasi digabungkan di satu tempat, file java sumber..
Listing 28.2. Listing 28.2. The Java ball class. Kelas bola Jawa.
class ball { class bola {
// Constants / / Konstanta
static final int COLOR_RED = 1; static final int COLOR_RED = 1;
static final int COLOR_YELLOW = 2; static final int COLOR_YELLOW = 2;
static final int COLOR_BLUE = 3; static final int COLOR_BLUE = 3;
static final int MATERIAL_RUBBER = 1; static final int MATERIAL_RUBBER = 1;
static final int MATERIAL_LEATHER = 2; static final int MATERIAL_LEATHER = 2;
// Variables / / Variabel
float diameter; float diameter;
int color; int warna;
int material; int bahan;
} }
The Java version of ball pulls all the constants inside the class definition as static final integers. Versi Jawa bola menarik semua konstanta di dalam definisi kelas sebagai bilangan bulat akhir statis. Within this class, you would then refer to them just as you would the previous C++ versions. Dalam kelas ini, Anda kemudian akan merujuk kepada mereka seperti halnya C + + versi sebelumnya. However, outside this class they are inaccessible, because they have been left at their default access type. Namun, di luar kelas ini mereka tidak dapat diakses, karena mereka telah ditinggalkan di jenis akses mereka default. To make them visible by other classes, you simply declare their access type as public , as shown in Listing 28.3. Untuk membuat mereka terlihat oleh kelas-kelas lain, Anda cukup menyatakan jenis akses mereka sebagai publik, seperti ditunjukkan pada Listing 28,3. The statement about default access isn't entirely true; you learn the whole scoop about access types later in this chapter. Pernyataan tentang akses default tidak sepenuhnya benar, anda mempelajari tentang jenis sendok seluruh akses kemudian dalam bab ini.
Listing 28.3. Listing 28,3. The Java ball class with public constants. Bola Jawa kelas dengan konstanta publik.
class ball { class bola {
// Constants / / Konstanta
public static final int COLOR_RED = 1; public static final int COLOR_RED = 1;
public static final int COLOR_YELLOW = 2; public static final int COLOR_YELLOW 2 =;
public static final int COLOR_BLUE = 3; public static final int COLOR_BLUE = 3;
public static final int MATERIAL_RUBBER = 1; public static final int MATERIAL_RUBBER = 1;
public static final int MATERIAL_LEATHER = 2; public static final int MATERIAL_LEATHER 2 =;
// Variables / / Variabel
float diameter; float diameter;
int color; int warna;
int material; int bahan;
} }
In this version of ball , the constants are readily available for other classes to use. Dalam versi ini bola, konstanta yang tersedia untuk kelas-kelas lain untuk digunakan. However, those classes must explicitly refer to the constants using the ball class name: Namun, kelas-kelas secara eksplisit harus mengacu pada konstanta menggunakan nama kelas bola:
int color = ball.COLOR_YELLOW; int color = ball.COLOR_YELLOW;
Structures and Unions Struktur dan Serikat
There are three types of complex data types in C/C++: classes, structures (structs), and unions. Ada tiga jenis tipe data yang kompleks di C / C + +: kelas, struktur (struct), dan serikat. Java supports only one of these data types, classes. Jawa hanya mendukung salah satu tipe data, kelas. Java forces programmers to use classes when the functionality of structures and unions is desired. Java pasukan pemrogram untuk menggunakan kelas ketika fungsi struktur dan serikat pekerja yang diinginkan. Although this sounds like more work for the programmer, it actually ends up being more consistent, because classes can imitate structures and unions with ease. Meskipun ini terdengar seperti pekerjaan lebih untuk programmer, itu benar-benar akhirnya menjadi lebih konsisten, karena class bisa meniru struktur dan serikat pekerja dengan mudah. Furthermore, supporting structs and unions would have put a major hole in the whole concept of the Java language being object-oriented. Selanjutnya, structs mendukung dan serikat pekerja akan telah menempatkan lubang besar di seluruh konsep dari bahasa Jawa yang berorientasi objek. The Java designers really wanted to keep the language simple, so it only made sense to eliminate aspects of the language that overlapped. Para desainer Jawa benar-benar ingin menjaga bahasa yang sederhana, sehingga hanya masuk akal untuk menghilangkan aspek bahasa yang tumpang tindih.Converting structs and unions to Java classes is pretty easy. Konversi structs dan serikat pekerja untuk kelas Java cukup mudah. Take a look at Listing 28.4, which contains a polar coordinate C struct. Lihatlah properti 28,4, yang berisi koordinat polar C struct.
Listing 28.4. Listing 28.4. The C polar struct. C kutub struct.
typedef struct polar { typedef struct {kutub
float angle; float sudut;
float magnitude float besarnya
} POLAR; } POLAR;
Notice that this struct uses a typedef to establish the polar type. Perhatikan bahwa ini menggunakan typedef struct untuk menetapkan jenis kutub. As you learned earlier, typedef s aren't necessary in Java, because everything is an object with a unique type. Seperti yang Anda pelajari sebelumnya, s typedef tidak perlu di Jawa, karena semuanya merupakan objek dengan tipe yang unik. Java doesn't support the concept of a struct either. Java tidak mendukung konsep struct baik. Listing 28.5 contains the Java version of the polar class. Properti 28,5 berisi versi Jawa kelas kutub.
Listing 28.5. Listing 28.5. The Java polar class. Kelas kutub Jawa.
class polar { kelas kutub {
float angle; float sudut;
float magnitude float besarnya
} }
In addition to changing the typedef struct declaration to class , notice that the Java polar class isn't followed by a semicolon. Selain mengubah typedef struct deklarasi tersebut ke kelas, perhatikan bahwa kelas Java kutub tidak diikuti dengan titik koma. This is a small, but often overlooked, difference between Java and C++; semicolons aren't necessary in Java class definitions . Ini adalah kecil, namun sering diabaikan, perbedaan antara Java dan C + +; titik koma tidak diperlukan dalam definisi class Java.
Functions and Methods Fungsi dan Metode
In C, code is organized into functions, which are global subroutines accessible to a program. Dalam C, kode ini disusun dalam fungsi yang subrutin global diakses program. C++ added classes and in doing so provided class methods, which are functions that are connected to classes. C + + kelas tambah dan dalam melakukan metode kelas itu disediakan, yang merupakan fungsi yang terhubung ke kelas. C++ class methods are very similar to Java class methods. C + + metode kelas yang sangat mirip dengan metode kelas Jawa. However, because C++ still supports C, there is nothing keeping C++ programmers from using functions. Namun, karena C + + masih mendukung C, tidak ada yang menjaga C + + programmer dari menggunakan fungsi. This results in a mixture of function and method use that makes for confusing programs. Hal ini menghasilkan campuran fungsi dan menggunakan metode yang membuat untuk program membingungkan.Java has no functions. Java tidak memiliki fungsi. Being a purer object-oriented language than C++, Java forces programmers to bundle all subroutines into class methods. Menjadi bahasa murni berorientasi obyek daripada C + +, Java memaksa programmer untuk bundel semua subrutin menjadi metode kelas. There is no limitation imposed by forcing programmers to use methods instead of functions. Tidak ada pembatasan yang dikenakan oleh memaksa programmer untuk menggunakan metode bukan fungsi. As a matter of fact, implementing subroutines as methods encourages programmers to organize code better. Sebagai soal fakta, menerapkan subrutin sebagai metode mendorong programmer untuk mengatur kode yang lebih baik. Keep in mind that, strictly speaking, there is nothing wrong with the procedural approach of using functions; it just doesn't mix well with the object-oriented paradigm that defines the core of Java. Perlu diketahui bahwa, tegasnya, tidak ada yang salah dengan pendekatan prosedural menggunakan fungsi; hal itu tidak bercampur dengan baik dengan paradigma berorientasi objek yang mendefinisikan inti Jawa.
Because almost all C/C++ code contains some degree of function use, this is a particularly important issue when porting C/C++ code to Java. Karena hampir semua C / C + + kode berisi beberapa derajat menggunakan fungsi, ini adalah masalah yang sangat penting saat port C / C + + kode ke Jawa. Fortunately, it's mostly an organizational change. Untungnya, itu sebagian besar perubahan organisasi. The whole point of functions is to move code into a logically separate procedure that can be called from the main program or other functions. Inti dari fungsi adalah dengan memindahkan kode ke prosedur logis terpisah yang dapat dipanggil dari program utama atau fungsi lainnya. You can easily recreate this scenario in Java without having to "objectify" the code completely. Anda dapat dengan mudah menciptakan skenario di Jawa tanpa harus "mengobjektifkan" kode sepenuhnya. The solution is to move global C/C++ functions into method-only organizational Java classes. Solusinya adalah dengan memindahkan global C / C + + fungsi ke dalam metode-hanya kelas Java organisasi. Check out Listing 28.6, which contains a series of string encryption/decryption function prototypes. Check out properti 28,6, yang berisi serangkaian prototipe dekripsi enkripsi string / fungsi.
Listing 28.6. Listing 28,6. The C string encryption/decryption function prototypes. String C fungsi enkripsi dekripsi prototipe /.
char EncryptChar(char c, int key); EncryptChar char (char c, int tombol);
char DecryptChar(char c, int key); DecryptChar char (char c, int tombol);
char* EncryptString(const char* s, int key); char * EncryptString (const char * s, int tombol);
char* DecryptString(const char* s, int key); char * DecryptString (const char * s, int tombol);
These functions are global C functions that encrypt and decrypt characters and strings. Fungsi-fungsi ini global C fungsi yang mengenkripsi dan mendekripsi karakter dan string. Of course, in C/C++ there is no pure concept of a string; an array of characters is the best you get (more on that later in this chapter). Tentu saja, di C / C + + tidak ada konsep murni string; sebuah array karakter adalah yang terbaik yang Anda dapatkan (lebih pada nanti dalam bab ini). A straight function-to-method port of these functions in Java is shown in Listing 28.7. Sebuah port fungsi-untuk-metode garis dari fungsi di Jawa ditampilkan pada Listing 28.7.
Listing 28.7. Listing 28.7. The Java string encryption/decryption methods encapsulated within the crypt class. Java string enkripsi / dekripsi metode dienkapsulasi dalam kelas crypt.
class crypt { class crypt {
public static char encryptChar(char c, int key) { public static encryptChar char (char c, int tombol) {
// character encryption code / / Karakter kode enkripsi
} }
public static char decryptChar(char c, int key) { public static decryptChar char (char c, int tombol) {
// character decryption code / / Karakter kode dekripsi
} }
public static String encryptString(String s, int key) { public static String encryptString (String s, int tombol) {
// string encryption code / / Enkripsi string kode
} }
public static String decryptString(String s, int key) { public static String decryptString (String s, int tombol) {
// string decryption code / / String kode dekripsi
} }
} }
In Java, you have to package the functions as methods in a class, crypt . Di Jawa, Anda harus paket fungsi sebagai metode di kelas, crypt. By declaring them as public static , you make them readily available to the entire Java system. Dengan menyatakan mereka sebagai public static, Anda membuat mereka tersedia untuk sistem Jawa keseluruhan. The key aspect of the Java version of the functions is that their implementations are defined in a Java class because Java doesn't support the header/source file organization. Aspek kunci dari versi Jawa fungsi adalah bahwa implementasi mereka didefinisikan dalam kelas Java karena Java tidak mendukung header / organisasi file source. All class information goes directly into the class definition. Semua informasi kelas masuk langsung ke dalam definisi kelas. Notice that the standard naming convention for Java methods is to begin each method name with a lowercase character. Perhatikan bahwa konvensi penamaan standar untuk metode Java adalah untuk memulai tiap nama metode dengan karakter huruf kecil. To use the Java methods, you have to reference them with the crypt class name: Untuk menggunakan metode Java, Anda harus referensi mereka dengan nama kelas crypt:
char c = crypt.encryptChar('a', 7); char c = crypt.encryptChar ('a', 7);
The only other change to the C functions is the usage of String objects rather than char pointers because Java doesn't support pointers. Yang lain hanya perubahan fungsi C adalah penggunaan obyek String bukan pointer char karena Jawa tidak mendukung pointer. You get into more details surrounding strings and pointers a little later in this chapter. Anda masuk ke rincian lebih lanjut sekitarnya string dan pointer sedikit kemudian dalam bab ini.
Procedural-to-OOP Conversion Prosedur-untuk OOP Konversi-
Although the Java crypt class provides working Java versions of the procedural C functions, performing this type of conversion isn't always enough. Meskipun kelas crypt Java menyediakan versi Jawa kerja fungsi C prosedural, melakukan jenis konversi tidak selalu cukup. The crypt class provides a good example of how you can maintain a procedural feel within a Java class. Kelas crypt memberikan contoh yang baik tentang bagaimana Anda dapat mempertahankan merasakan prosedural dalam kelas Java. Java is an object-oriented language, however, and you should design your code to fit into the object-oriented paradigm whenever possible. Java adalah bahasa berorientasi objek, bagaimanapun, dan Anda harus merancang kode Anda cocok dengan paradigma berorientasi objek bila memungkinkan. The crypt class is no exception to this rule. Kelas crypt bukan pengecualian dari aturan ini.Examining the crypt class methods, it is apparent that some things could be modified to make the class fit into a more object-oriented design. Meneliti metode kelas crypt, jelaslah bahwa beberapa hal dapat dimodifikasi untuk membuat sesuai kelas ke dalam desain yang lebih berorientasi objek. Listing 28.8 contains the source code for the revised, objectified crypt class. Listing 28.8 berisi kode sumber untuk crypt, kelas objektifikasi direvisi.
Listing 28.8. Listing 28.8. The revised Java >crypt class. Java revisi> crypt kelas.
class crypt { class crypt {
int key; int kunci;
crypt(int k) { crypt (int k) {
key = k; key = k;
} }
void setKey(int k) { void setKey (int k) {
key = k; key = k;
} }
int getKey() { int getKey () {
return key; mengembalikan kunci;
} }
char encryptChar(char c) { encryptChar char (char c) {
// character encryption code / / Karakter kode enkripsi
} }
char decryptChar(char c) { decryptChar char (char c) {
// character decryption code / / Karakter kode dekripsi
} }
String encryptString(String s) { EncryptString String (String s) {
// string encryption code / / Enkripsi string kode
} }
String decryptString(String s) { DecryptString String (String s) {
// string decryption code / / String kode dekripsi
} }
} }
In this version of crypt , the encryption key has been moved from a method parameter to a data member of the class, key . Dalam versi ini crypt, kunci enkripsi telah dipindahkan dari sebuah parameter metode untuk data anggota kelas, kunci. A constructor was added that accepts an encryption key when the object is created, along with access methods for getting and setting the key. Sebuah konstruktor ditambahkan yang menerima kunci enkripsi ketika objek dibuat, bersama dengan metode akses untuk mendapatkan dan pengaturan kunci. The public static declarations for the encrypt/decrypt methods have also been removed, which requires you to have an instance of the crypt class to use the methods. Deklarasi public static untuk mengenkripsi / mendekripsi metode juga telah dihapus, yang mengharuskan Anda untuk memiliki sebuah instance dari kelas crypt menggunakan metode. This makes sense, because the class now has a data member ( key ) that affects the methods. Ini masuk akal, karena kelas sekarang memiliki anggota data (tombol) yang mempengaruhi metode.
This revised design of the crypt class makes much more sense from a Java programming perspective. Rancangan revisi kelas crypt masuk akal jauh lebih dari perspektif pemrograman Java. Of course, it won't run any faster or perform better encryption, but that's not the point. Tentu saja, itu tidak akan berjalan lebih cepat atau melakukan enkripsi lebih baik, tapi bukan itu intinya. The point is that object-oriented design practices are a fundamental part of the Java language and should be followed whenever possible. Intinya adalah bahwa praktek desain berorientasi objek adalah bagian mendasar dari bahasa Jawa dan harus diikuti bila memungkinkan.
Operator Overloading Operator Overloading
Operator overloading, which is considered a prominent feature in C++, is not supported in Java. Operator overloading, yang dianggap sebagai ciri yang menonjol dalam C + +, tidak didukung di Jawa. Although roughly the same functionality can be implemented as methods in Java classes, the syntactic convenience of operator overloading is still missing. Meskipun sekitar fungsi yang sama dapat diterapkan sebagai metode di kelas Jawa, kenyamanan sintaksis operator overloading masih hilang. However, in defense of Java, operator overloading can sometimes get very tricky. Namun, dalam pertahanan Jawa, operator overloading kadang-kadang bisa menjadi sangat rumit. The Java developers decided not to support operator overloading to keep the Java language as simple as possible. Para pengembang Java memutuskan untuk tidak mendukung operator overloading untuk menjaga bahasa Jawa sesederhana mungkin.Although operator overloading is a pretty useful feature in C++, its usage is highly dependent on the types of C++ classes with which you're dealing. Meskipun operator overloading adalah fitur yang cukup berguna dalam C + +, penggunaannya sangat tergantung pada jenis kelas C + + dengan yang Anda hadapi. For example, more fundamental C++ data structure classes, such as string classes, make heavy use of operator overloading, whereas others may not use it all. Sebagai contoh, lebih mendasar C + + data struktur kelas, seperti kelas string, menggunakan operator overloading berat, sedangkan yang lain mungkin tidak menggunakan semuanya. The amount of porting work you have in front of you depends on how much your C++ code relies on operator overloading. Jumlah pekerjaan port yang ada di depan Anda tergantung pada seberapa banyak C + + kode bergantung pada operator overloading.
The only way to convert overloaded C++ operators to Java is to create equivalent Java methods with the same functionality. Satu-satunya cara untuk mengkonversi overloaded C + + operator ke Jawa adalah untuk menciptakan metode Jawa setara dengan fungsi yang sama. Keep in mind that the Java methods will be called differently than the C++ overloaded operators. Perlu diketahui bahwa metode Java akan dipanggil berbeda dari C + + overload operator. This means you have to dissect your code carefully to find out where each operator is used and then convert the code to a method call. Ini berarti Anda harus membedah kode Anda hati-hati untuk mencari tahu di mana masing-masing operator digunakan dan kemudian dikonversi kode untuk pemanggilan metode.
Let's look at an example; Listing 28.9 contains a complex number class with overloaded operators. Mari kita lihat contoh; properti 28,9 berisi kelas bilangan kompleks dengan operator kelebihan beban.
Listing 28.9. Listing 28.9. The C++ Complex class with overloaded operators. C + + class Kompleks dengan operator kelebihan beban.
class Complex { class Kompleks {
float real; float real;
float imaginary; float imajiner;
Complex(float r, float i); Kompleks (float r, float i);
Complex operator+(const Complex& c) const { Kompleks operator + (const Complex & c) const {
return Complex(real + c.real, imaginary + c.imaginary); kembali Complex (real + c.real, khayalan + c.imaginary);
} }
Complex operator-(const Complex& c) const { Kompleks operator-(const Complex & c) const {
return Complex(real - c.real, imaginary - c.imaginary); kembali Complex (real - c.real, imajiner - c.imaginary);
} }
}; };
The C++ Complex number class supports overloaded operators for addition and subtraction. C + + kelas nomor Kompleks mendukung operator overloaded untuk penambahan dan pengurangan. The following is an example of how this class is used: Berikut ini adalah contoh bagaimana kelas ini digunakan:
Complex c1(3.0, 4.0); Kompleks c1 (3.0, 4.0);The subtraction of the Complex objects is syntactically the same as subtracting two fundamental data types. The pengurangan objek Kompleks sintaktis sama dengan mengurangi dua jenis data mendasar. However, this capability adds a significant amount of complexity to C++ that the Java architects wanted to avoid. Namun, kemampuan ini menambah jumlah yang signifikan kompleksitas ke C + + bahwa arsitek Jawa ingin menghindari. So, although you can't provide the same syntactic approach in Java, you can provide methods with similar functionality. Jadi, walaupun Anda tidak dapat menyediakan pendekatan sintaktis yang sama di Jawa, anda dapat menyediakan metode dengan fungsi serupa. Listing 28.10 contains the Java version of the Complex class, complete with method versions of the overloaded operators. Daftar 28,10 berisi versi Jawa kelas Kompleks, lengkap dengan versi metode operator kelebihan beban.
Complex c2(5.0, 2.5); Kompleks c2 (5.0, 2.5);
Complex c3 = c2 - c1; Complex c3 = c2 - c1;
Listing 28.10. Listing 28,10. The Java Complex class. Kelas Kompleks Jawa.
class Complex { class Kompleks {
float real; float real;
float imaginary; float imajiner;
Complex(float r, float i) { Kompleks (float r, float i) {
real = r; real = r;
imaginary = i; imajiner = i;
} }
Complex add(Complex c) { Kompleks add (Complex c) {
return (new Complex(real + c.real, imaginary + c.imaginary)); kembali (baru Complex (real + c.real, khayalan + c.imaginary));
} }
Complex subtract(Complex c) { Kompleks mengurangi (c Kompleks) {
return (new Complex(real - c.real, imaginary - c.imaginary)); kembali (baru Complex (real - c.real, imajiner - c.imaginary));
} }
} }
The most obvious change in the Java version of Complex is the renaming of the operator overloaded methods to add and subtract . Yang jelas Perubahan yang paling dalam versi Jawa Kompleks adalah penggantian nama dari operator metode kelebihan beban untuk menambah dan mengurangi. The Java Complex class is used like this: Kompleks class Java yang digunakan seperti ini:
Complex c1 = new Complex(3.0, 4.0); c1 Kompleks baru Kompleks = (3.0, 4.0);You can see how the subtraction operation isn't quite as intuitive using the Java approach. Anda dapat melihat bagaimana operasi pengurangan tidak cukup sebagai intuitif menggunakan pendekatan Java. Nevertheless, it does work. Namun demikian, itu tidak bekerja. Notice also that the Complex objects are created using the new operator. Perhatikan juga bahwa obyek Kompleks dibuat menggunakan operator baru. This is a result of the differences between memory management in Java and C++, which you learn about when you get into pointers a little later in this chapter. Ini merupakan hasil dari perbedaan antara manajemen memori di Jawa dan C + +, yang Anda belajar tentang kapan Anda masuk ke pointer sedikit kemudian dalam bab ini.
Complex c2 = new Complex(5.0, 2.5); Kompleks c2 baru Kompleks = (5.0, 2.5);
Complex c3 = c2.subtract(c1); Complex c3 = c2.subtract (c1);
Automatic Coercions Otomatis Coercions
Automatic coercion refers to the implicit casting of data types that sometimes occurs in C and C++. pemaksaan Otomatis mengacu pada casting implisit jenis data yang kadang-kadang terjadi di C dan C + +. For example, in C++ you are allowed to assign a float value to an int variable, which can result in a loss of information. Misalnya, di C + + Anda diijinkan untuk menetapkan nilai float ke variabel int, yang dapat mengakibatkan hilangnya informasi. Java does not support C++ style automatic coercions. Java tidak mendukung C + + coercions otomatis gaya. In Java, if a coercion will result in a loss of data, you must always explicitly cast the data element to the new type. Di Jawa, jika pemaksaan akan mengakibatkan hilangnya data, Anda harus selalu eksplisit melemparkan elemen data ke tipe baru.The following is an example of an automatic coercion in C++: Berikut ini adalah contoh dari pemaksaan otomatis di C + +:
float f = 3.1412; float f = 3,1412;Some C++ compilers may actually generate a warning for this code, but it's not considered an error. C + + compiler Beberapa benar-benar dapat menghasilkan peringatan untuk kode ini, tapi itu tidak dianggap kesalahan. In Java, on the other hand, this code results in a compile error. Di Jawa, di sisi lain, hasil kode ini dalam sebuah kompilasi kesalahan. It is easily fixed with an explicit cast, such as this: Hal ini mudah diperbaiki dengan cor eksplisit, seperti ini:
int i = f; int i = f;
float f = 3.1412; float f = 3,1412;
int i = (int)f; int i = (int) f;
Command-Line Arguments Argumen Command-Line
The command-line arguments passed from the system into a Java program differ in a couple of ways from the command-line arguments passed into a C++ program. Argumen baris perintah lulus dari sistem ke program Java berbeda dalam beberapa cara dari argumen baris perintah dilewatkan ke dalam C + + program. First, the number of parameters passed differs between the two languages. Pertama, jumlah parameter yang dikirimkan berbeda antara kedua bahasa tersebut. In C and C++, the system passes two arguments to a program: argc and argv . argc specifies the number of arguments stored in argv . argv is a pointer to an array of character pointers containing the actual arguments. Dalam C dan C + +, sistem melewati dua argumen untuk program: dan argv. Argc argc menentukan jumlah argumen yang tersimpan dalam argv argumen. Argv adalah pointer ke array karakter pointer berisi sebenarnya. In Java, the system passes a single value to a program: args . args is an array of String objects that contains the command-line arguments. Di Jawa, sistem melewati nilai tunggal untuk program:. Args args adalah array dari objek String yang berisi argumen-baris perintah.In C and C++, the command-line arguments passed into a program include the name used to invoke the program. Dalam C dan C + +, argumen command-line dilewatkan ke dalam sebuah program termasuk nama yang digunakan untuk memanggil program. This name always appears as the first argument, and it is rarely used. Nama ini selalu muncul sebagai argumen pertama, dan jarang digunakan. In Java, you already know the name of the program because it is the same name as the class, so there is no need to pass this information as a command-line argument. Di Jawa, Anda sudah tahu nama program karena itu adalah nama yang sama sebagai kelas, sehingga tidak perlu untuk melewatkan informasi ini sebagai sebuah argumen baris perintah. Therefore, the Java runtime system passes only the arguments following the name that invoked the program. Oleh karena itu, sistem runtime Jawa hanya lewat argumen berikut nama yang dipanggil program.
Listing 28.11 contains a simple C++ program that prints out the argument list. 28.11 berisi daftar sederhana C + + program yang mencetak daftar argumen.
Listing 28.11. Listing 28.11. A C++ program to print the argument list. A C + + program untuk mencetak daftar argumen.
#include <iostream.h> # Include <iostream.h>
#include <string.h> # Include <string.h>
void main(int argc, char* argv[]) void main (int argc, char * argv [])
{ {
for(int i = 1; i < argc; i++) for (int i = 1; i <argc; i + +)
cout << argv[i] << "\n"; cout <<argv [i] <<"\ n";
} }
This program simply iterates through each argument using a for loop, printing each to the standard output stream. Program ini hanya beriterasi setiap argumen dengan menggunakan perulangan for, mencetak masing-masing ke stream output standar. Notice that the loop starts at 1 to avoid printing the name of the program itself (the first argument). Perhatikan bahwa loop dimulai pada 1 untuk menghindari pencetakan nama program itu sendiri (argumen pertama). Listing 28.12 contains the Java equivalent, the ArgPrint application class. Daftar 28.12 berisi setara Jawa, kelas aplikasi ArgPrint.
Listing 28.12. Listing 28.12. The Java ArgPrint class. Java ArgPrint kelas.
public class ArgPrint { public class ArgPrint {
public static void main(String[] args) { public static void main (String [] args) {
for (int i = 0; i < args.length; iI++) for (int i = 0; i <args.length; iI+ +)
System.out.println(args[i]); System.out.println (args [i]);
} }
} }
The ArgPrint class contains one method, the main method. Kelas ArgPrint mengandung satu metode, metode utama. This is the Java equivalent of the C/C++ main function; it is called when the Java program is executed. Ini adalah setara Java C / C + + fungsi utama, melainkan dipanggil saat program Java dijalankan. Notice that the main method takes an array of String objects as parameters. Perhatikan bahwa metode utama mengambil array obyek String sebagai parameter. The usage of this array highlights another interesting difference between Java and C++, arrays. Penggunaan array ini menyoroti perbedaan lain yang menarik antara Java dan C + +, array. All Java arrays have a data member called length that can be used to determine how many elements an array contains. Semua array Jawa mempunyai anggota disebut panjang data yang dapat digunakan untuk menentukan berapa banyak elemen array berisi. In this case, length is used to iterate through the array of String arguments. Dalam hal ini, panjang digunakan untuk iterate melalui array dari argumen String.
I/O Streams I / O Streams
You probably noticed the absence of the cout standard output stream object in the Java ArgPrint class. Anda mungkin melihat adanya standar objek stream output pengadilan di kelas ArgPrint Jawa. There's a good reason for this: Java doesn't implement any of the standard C++ stream objects. Ada alasan yang baik untuk ini: Java tidak menerapkan salah satu standar C + + obyek stream. However, it does contain similar equivalents. Namun, itu tidak mengandung setara sama. The Java System class implements three stream objects that are very similar to the C++ standard stream objects: in , out , and err . Sistem kelas Java mengimplementasikan objek tiga sungai yang sangat mirip dengan C + + objek aliran standar:, keluar, dan salah. You access these stream objects with the System class. Anda mengakses obyek stream dengan kelas Sistem.The ArgPrint class showed how to use the out stream object to output text. Kelas ArgPrint menunjukkan bagaimana menggunakan objek aliran keluar ke teks output. The out object is of type OutputStream , and it contains a number of methods, such as println , for outputting data to the standard output stream. Objek keluar adalah OutputStream jenis, dan berisi sejumlah metode, seperti println, untuk keluaran data ke output stream standar. Similarly, the in and err objects contain a variety of methods for performing stream input and output. Demikian pula, dalam dan keliru benda mengandung berbagai metode untuk melakukan stream input dan output. In most cases, you can convert standard C++ stream I/O code to Java stream I/O code by simply changing the references from cin to System.in , and so forth. Dalam kebanyakan kasus, Anda dapat mengkonversi standar C + + I stream / O kode untuk melakukan streaming Java I / O kode hanya dengan mengubah referensi dari cin ke System.in, dan sebagainya. Because Java doesn't support operator overloading, you also need to change any << or >> operations to the equivalent Java method calls. Karena Java tidak mendukung operator overloading, Anda juga perlu mengubah <<atau>> operasi untuk panggilan metode Java setara.
Strings String
C and C++ have no built-in support for text strings. C dan C + + tidak memiliki built-in mendukung untuk string teks. The standard technique adopted among C and C++ programmers is that of using null-terminated arrays of characters to represent strings. Teknik standar yang diadopsi antara C dan C + + programmer adalah menggunakan array-dihentikan null karakter untuk mewakili string. In Java, strings are implemented as first class objects ( String and StringBuffer ), meaning that they are at the core of the Java language. Di Jawa, string diimplementasikan sebagai obyek kelas pertama (String dan StringBuffer), yang berarti bahwa mereka adalah inti dari bahasa Jawa. Java's implementation of strings as objects provides several advantages: Jawa implementasi string sebagai obyek memberikan beberapa keuntungan:- The manner in which you create strings and access the elements of strings is consistent across all strings on all systems. Cara di mana Anda membuat string dan mengakses elemen string konsisten di semua senar pada semua sistem.
- Because the Java string classes are defined as part of the Java language, and not part of some extraneous extension, Java strings function predictably every time. Karena kelas-kelas Jawa string didefinisikan sebagai bagian dari bahasa Jawa, dan bukan bagian dari beberapa ekstensi asing, Jawa string fungsi diramalkan setiap waktu.
- The Java string classes perform extensive runtime checking, which helps eliminate troublesome runtime errors. Kelas Jawa string melakukan pemeriksaan runtime luas, yang membantu menghilangkan error runtime merepotkan.
Listing 28.13 contains a simple C++ function that manipulates null-terminated character strings, ReverseIt . 28,13 berisi daftar sederhana C + + fungsi yang memanipulasi diakhiri null-string karakter, ReverseIt.
Listing 28.13. Listing 28.13. The C++ ReverseIt function. C + + fungsi ReverseIt.
char* ReverseIt(const char* szText) { char * ReverseIt (const char * szText) {
int len = strlen(szText); int len = strlen (szText);
char* dest = new char[len]; Char * dest = new char [len];
for (i = (len - 1); i ><= 0; i--) for (i = (len - 1); i><=0; i -)
dest[len - i - 1] = szText[i]; dest [len - i - 1] = szText [i];
return dest; return dest;
} }
The ReverseIt function takes an array of characters and returns an array of characters that is the reverse of the original. Fungsi ReverseIt menggunakan sebuah array karakter dan mengembalikan array karakter yang adalah kebalikan dari yang asli. It simply creates a new array and copies each character from the original array in reverse order. Ini hanya menciptakan array baru dan salinan setiap karakter dari array yang asli dalam urutan terbalik. Notice, however, that there is nothing stopping you from writing code that overruns an array bound, or even from manipulating the character pointers. Perhatikan, bagaimanapun, bahwa tidak ada yang menghentikan Anda dari menulis kode yang overruns array terikat, atau bahkan dari memanipulasi pointer karakter. Even though this code works fine, the very nature of C++ makes it prone to potentially dangerous pitfalls implemented at the programmer's discretion. Meskipun kode ini berfungsi dengan baik, sifat dari C + + membuat rentan terhadap perangkap yang berbahaya diimplementasikan pada kebijaksanaan programmer. Take a look at the Java version of the same function, reverseIt , which is now a method in the Reverse class in Listing 28.14. Lihatlah versi Jawa dari reverseIt, fungsi yang sama, yang kini sebuah metode Reverse kelas pada Listing 28,14.
Listing 28.14. Listing 28,14. The Java Reverse class. Java Reverse kelas.
class Reverse { Reverse class {
String reverseIt(String s) { ReverseIt String (String s) {
int i, len = s.length(); int i, len = s.length ();
StringBuffer dest = new StringBuffer(len); Dest = new StringBuffer StringBuffer (len);
for (i = (len - 1); i >= 0; i--) for (i = (len - 1); i> = 0; i -)
dest.append(s.charAt(i)); dest.append (s.charAt (i));
return dest.toString(); kembali dest.toString ();
} }
} }
The Java reverseIt method has no mention or use of arrays. Metode Jawa reverseIt tidak menyebutkan atau penggunaan array. In Java, strings are first class citizens implemented by the String and StringBuffer classes; they are genuine data types that can be manipulated like integers or floating-point numbers. Di Jawa, string adalah warga kelas pertama kali diimplementasikan oleh String dan kelas StringBuffer; mereka asli tipe data yang dapat dimanipulasi seperti integer atau angka floating-point. All modifications to Java strings must take place through the class methods defined in the String and StringBuffer classes, as you can see in the reverseIt method. Semua modifikasi string Jawa harus dilakukan melalui metode kelas yang didefinisikan di kelas String dan StringBuffer, seperti yang Anda lihat dalam metode reverseIt.
Pointers Pointer
Most developers agree that the misuse of pointers causes the majority of bugs in C/C++ programming. Kebanyakan pengembang setuju bahwa penyalahgunaan pointer menyebabkan sebagian besar bug di pemrograman C / C + +. Put simply, when you have pointers, you have the ability to trash memory. Sederhananya, bila Anda memiliki pointer, Anda memiliki kemampuan untuk sampah memori. C++ programmers regularly use complex pointer arithmetic to create and maintain dynamic data structures. C + + programmer secara teratur menggunakan pointer arithmetic kompleks untuk membuat dan memelihara struktur data dinamis. In return, C++ programmers spend a lot of time hunting down complex bugs caused by their complex pointer arithmetic. Sebagai imbalannya, C + + programmer menghabiskan banyak waktu di bawah berburu bug kompleks disebabkan oleh aritmetik pointer kompleks mereka.The Java language does not support pointers. Bahasa Java tidak mendukung pointer. Java provides similar functionality by making heavy use of references. Java menyediakan fungsi serupa dengan memanfaatkan referensi berat. Java passes all arrays and objects by reference. Java melewati semua array dan objek dengan referensi. This approach prevents common errors due to pointer mismanagement. Pendekatan ini mencegah kesalahan umum karena salah urus pointer. It also makes programming easier in a lot of ways, because the correct usage of pointers is easily misunderstood by all but the most seasoned programmers. Hal ini juga membuat programming lebih mudah dalam banyak cara, karena pemakaian yang benar atas pointer mudah disalahpahami oleh semua tetapi kebanyakan programmer berpengalaman.
You may be thinking that the lack of pointers in Java will keep you from being able to implement many data structures, such as dynamically growable arrays. Anda mungkin berpikir bahwa kurangnya pointer di Jawa akan menjaga Anda dari mampu melaksanakan banyak struktur data, seperti array dinamis growable. The reality is that any pointer task can be carried out just as easily and more reliably with objects and references. Kenyataannya adalah bahwa setiap tugas pointer dapat dilakukan dengan mudah dan lebih handal dengan benda-benda dan referensi. You then benefit from the security provided by the Java runtime system; it performs boundary checking on all array indexing operations. Anda kemudian mendapatkan keuntungan dari keamanan yang disediakan oleh sistem runtime Jawa; ia melakukan pengecekan batas pada semua operasi pengindeksan array.
Pointers are no doubt the most difficult aspect of moving C/C++ code to Java, because most C/C++ programs are riddled with pointer use. Penunjuk adalah tidak diragukan lagi aspek yang paling sulit bergerak C / C + + kode ke Jawa, karena kebanyakan C / C + + program-program yang penuh dengan menggunakan pointer. The first line of attack in converting pointer code is to convert all character arrays to Java strings. Baris pertama serangan dalam mengkonversi kode pointer adalah untuk mengkonversi semua array string karakter ke Jawa. Once you do this, you'll probably be surprised at how much pointer-dependent code was weeded out. Setelah Anda melakukan ini, Anda mungkin akan terkejut melihat bagaimana kode penunjuk-tergantung banyak yang terpangkas.
The next phase of pointer conversion is object creation/destruction. Tahap berikutnya konversi pointer objek penciptaan / kehancuran. In C++, the typical way objects are used is to create a pointer to an object variable and then use the new operator to create a new object and assign it to the variable. Dalam C + +, obyek cara khas yang digunakan adalah untuk membuat pointer ke variabel objek dan kemudian menggunakan operator baru untuk membuat objek baru dan menetapkan ke variabel. Once you finish with the object, you call delete on the pointer variable to clean up things. Setelah Anda selesai dengan objek, Anda menelepon menghapus pada variabel pointer untuk membersihkan sesuatu. This procedure isn't all that different in Java; it's just missing the final step. Prosedur ini tidak semua yang berbeda di Jawa, itu hanya hilang langkah terakhir.
In Java, objects no longer being used are automatically cleaned up by the Java garbage collection system, which is typically implemented as a low-priority system thread. Di Jawa, objek tidak digunakan lagi secara otomatis dibersihkan oleh sistem pengumpulan sampah Jawa, yang biasanya diimplementasikan sebagai benang sistem yang rendah-prioritas. Because the Java system itself handles cleaning up unused objects, you don't have to worry about cleaning up after yourself. Karena sistem Jawa itu sendiri menangani membersihkan objek yang tidak digunakan, Anda tidak perlu khawatir tentang pembersihan setelah sendiri. This may be your one opportunity to make a mess and not have to clean up after yourself, so take advantage of it! Ini mungkin satu kesempatan Anda untuk membuat berantakan dan tidak harus membersihkan setelah diri sendiri, jadi mengambil keuntungan dari itu! To better understand the differences between working with objects and pointers in C++ and Java, let's look at an example. Untuk lebih memahami perbedaan antara bekerja dengan benda-benda dan pointer di C + + dan Java, mari kita lihat sebuah contoh. Listing 28.15 contains a C++ class with a member object pointer. 28,15 berisi daftar C + + kelas dengan objek penunjuk anggota.
Listing 28.15. Listing 28,15. The C++ Rocket class. C + + kelas Rocket.
class Rocket { Rocket class {
Booster* booster = 0; Booster * booster = 0;
Rocket() { Rocket () {
booster = new Booster(); booster baru Booster = ();
} }
~Rocket() { ~ Rocket () {
if (booster != 0) { if (booster 0! =) {
delete booster; menghapus booster;
booster = 0; booster = 0;
} }
} }
}; };
The constructor for Rocket initializes the booster member variable by creating a new object. Konstruktor untuk Rocket menginisialisasi variabel anggota booster dengan menciptakan sebuah objek baru. Then the destructor for Rocket cleans up the booster member by deleting it and setting it to 0 . Kemudian destructor untuk Rocket membersihkan anggota booster dengan menghapus dan setting ke 0. This is a painfully simple example, but it helps to learn things in small doses. Ini adalah contoh menyakitkan sederhana, tetapi hal ini membantu untuk belajar hal-hal dalam dosis kecil. Listing 28.16 contains the Java version of this same class. Daftar 28.16 berisi versi Jawa ini kelas yang sama.
Listing 28.16. Listing 28.16. The Java Rocket class. Java Rocket kelas.
class Rocket { Rocket class {
Booster booster; Booster booster;
Rocket() { Rocket () {
booster = new Booster(); booster baru Booster = ();
} }
} }
The Java code is much more simpler, even in this case where there is relatively little happening with the C++ pointers. Kode Java jauh lebih sederhana, bahkan dalam kasus di mana ada relatif sedikit terjadi dengan C + + pointer. Notice that the booster member variable isn't initialized to 0 in the Java version of Rocket . Perhatikan bahwa variabel anggota booster tidak diinisialisasi ke 0 dalam versi Jawa Rocket. This highlights a subtle feature in Java; all member variables are set to 0 or null if they are created without being initialized. Ini menyoroti fitur halus di Jawa; semua variabel anggota diatur ke 0 atau null jika mereka diciptakan tanpa diinisialisasi. Notice also the absence of a destructor in the Java code; the Java garbage collector takes care of cleaning up the booster object when it is no longer in use. Perhatikan juga adanya destructor dalam kode Java, pengumpul sampah Jawa mengurus membersihkan objek booster bila tidak lagi digunakan.
| Note Catatan |
Java actually supports a method very similar to a C++ destructor, the finalize method. Jawa sebenarnya mendukung metode yang sangat mirip dengan C + + destructor, yang menyelesaikan metode. The finalize method is called whenever an object is destroyed by the garbage collector. Metode merampungkan disebut ketika sebuah objek dihancurkan oleh garbage collector. However, due to the nature of the garbage collector itself, Java does not guarantee that the finalize method will get called for all objects. Namun, karena sifat para kolektor sampah sendiri, Jawa tidak menjamin bahwa metode menyelesaikan akan mendapatkan dipanggil untuk semua objek. In other words, don't rely on it getting called in your code! Dengan kata lain, tidak bergantung pada itu mendapatkan disebut dalam kode Anda! |
Multiple Inheritance Beberapa Warisan
Multiple inheritance is a feature of C++ that enables you to derive a class from multiple parent classes. Beberapa warisan adalah fitur C + + yang memungkinkan Anda untuk mendapatkan kelas dari kelas induknya ganda. Although multiple inheritance is indeed powerful, it is complicated to use correctly and causes lots of problems otherwise. Walaupun multiple inheritance memang kuat, adalah rumit untuk digunakan dengan benar dan menyebabkan banyak masalah lain. It is also very complicated to implement from the compiler perspective. Hal ini juga sangat rumit untuk mengimplementasikan dari perspektif compiler.Java takes the high road and provides no direct support for multiple inheritance. Jawa mengambil jalan yang tinggi dan tidak memberikan dukungan langsung untuk multiple inheritance. You can implement functionality similar to multiple inheritance by using interfaces in Java. Anda dapat menerapkan fungsionalitas yang sama dengan multiple inheritance dengan menggunakan antarmuka di Jawa. Java interfaces provide object method descriptions, but contain no implementations. Jawa interface memberikan deskripsi objek metode, tetapi tidak mengandung implementasi. Let's take a look at an example of C++ code that uses multiple inheritance: Mari kita lihat sebuah contoh kode C + + yang menggunakan turunan:
class InputDevice : public Clickable, public Draggable { kelas InputDevice: clickable publik, draggable publik {The C++ InputDevice class is derived both from the Clickable and Draggable classes. C + + class InputDevice berasal baik dari dan draggable kelas clickable. This means that InputDevice inherits all the data members and methods implemented in both of these classes. Ini berarti bahwa semua anggota InputDevice mewarisi data dan metode diterapkan di kedua kelas. The closest you can get to this in Java is to make Clickable and Draggable interfaces, which can contain method definitions but no actual method code or data members. Yang paling dekat Anda bisa mendapatkan ini di Jawa adalah untuk membuat dan draggable clickable interface, yang dapat berisi definisi metode tapi tidak ada kode metode aktual atau anggota data. The InputDevice class can implement these interfaces using the implements keyword: Kelas InputDevice dapat mengimplementasikan antarmuka ini menggunakan menerapkan kata kunci:
// class definition / / Definisi kelas
}; };
class InputDevice implements Clickable, Draggable { InputDevice kelas mengimplementasikan Diri, draggable {As you can see, you may have your work cut out for you if you are trying to move C++ code to Java that relies on lots of multiply inherited classes. Seperti yang Anda lihat, Anda mungkin memiliki pekerjaan Anda cocok untuk Anda jika Anda mencoba untuk memindahkan C + + kode ke Jawa yang bergantung pada banyak berkembang biak kelas diwariskan. Even so, the Java interface approach is not all that bad; you just have to juggle the actual method bodies and possibly implement more derived classes to contain them. Meskipun demikian, pendekatan antarmuka Java tidak semua yang buruk, Anda hanya perlu menyeimbangkan badan metode aktual dan mungkin menerapkan kelas lebih diturunkan mengandung mereka. Nevertheless, the primary goal of uniting separate logical organizations into a more derived one will still be attained. Namun demikian, tujuan utama menyatukan organisasi logis terpisah menjadi lebih berasal satu masih akan tercapai.
// class definition / / Definisi kelas
} }
Inheritance Syntax Warisan Sintaks
The multiple inheritance example brings up another important difference between C++ and Java: inheritance syntax. Contoh multiple inheritance membawa lagi perbedaan penting antara C + + dan Java: sintaks warisan. In C++, you specify inheritance by using a colon after the newly derived class, followed by the parent class or classes: Dalam C + +, Anda menetapkan warisan dengan menggunakan tanda titik dua setelah kelas baru diturunkan, diikuti oleh kelas induk atau kelas:class B : public A { kelas B: public A {In Java, the extends and implements keywords are used to indicate inheritance: Di Jawa, meluas dan menerapkan kata kunci yang digunakan untuk menunjukkan warisan:
// class definition / / Definisi kelas
}; };
class B extends A { Kelas B extends A {Fortunately, this change can be made in your C++ code as a simple search and replace, for the most part. Untungnya, perubahan ini dapat dibuat dalam C + + kode sebagai pencarian sederhana dan mengganti, untuk sebagian besar. The only hangup will be changing the syntax for classes using multiple inheritance, in which case you have to do some real work anyway. Para hangup hanya akan mengubah sintaks untuk kelas menggunakan multiple inheritance, dalam hal ini Anda harus melakukan beberapa pekerjaan nyata pula.
// class definition / / Definisi kelas
} }
Access Modifiers Akses Pengubah
Access modifiers are supported in both C++ and Java, but the methods of declaring them are different in each. Akses pengubah didukung di kedua C + + dan Java, tetapi metode menyatakan mereka berbeda di masing-masing. In C++, you declare access modifiers as a label above a group of class members: Dalam C + +, Anda menyatakan pengubah akses sebagai label di atas sekelompok anggota kelas:class A { kelas A {In Java, you can do the same thing, but you apply the access modifiers a little differently. Di Jawa, Anda dapat melakukan hal yang sama, tetapi anda menerapkan pengubah akses sedikit berbeda. You set them for each individual declaration: Anda menetapkan mereka untuk setiap pernyataan individu:
public: publik:
int x, y; int x, y;
private: swasta:
float v; float v;
}; };
class A { kelas A {In this way, Java access modifiers aren't labels at all; they really are modifiers. Dengan cara ini, pengubah Jawa akses tidak label sama sekali, mereka benar-benar pengubah. Converting access modifiers in C++ code is pretty simple; just go through and remove each label, adding the appropriate modifier to each variable declaration or method following the original label. Konversi pengubah akses di C + + kode ini cukup sederhana, cukup melewati dan menghapus label masing-masing, menambahkan pengubah yang tepat untuk setiap deklarasi variabel atau metode berikut label asli.
public int x, y; public int x, y;
private float v; private float v;
} }
Friends and Packages Teman dan Paket
Java has no friends! Java tidak memiliki teman! To prove it to you, Java doesn't have any concept of a friend class, whereas C++ does. Untuk membuktikan kepada Anda, Java tidak memiliki konsep class teman, sedangkan C + + tidak. A friend class in C++ is one that has access to all the data and methods in another class, regardless of the visibility of the member data. Sebuah kelas teman di C + + adalah salah satu yang memiliki akses ke semua data dan metode di kelas lain, terlepas dari visibilitas data anggota. Java has no exact equivalent to the friend concept, but it does have an access type that enables a specific group of classes access to member data, which is somewhat similar to the friend idea. Java tidak setara yang tepat untuk konsep teman, tetapi tidak memiliki jenis akses yang memungkinkan kelompok tertentu akses kelas untuk data anggota, yang agak mirip dengan ide teman.This Java access type is often referred to as the default type, because there is no keyword used to apply it. Jenis akses Jawa sering disebut sebagai tipe default, karena tidak ada kata kunci yang digunakan untuk menerapkannya. You may also see it referred to as the friendly access modifier. Anda juga dapat melihat itu disebut sebagai pengubah akses ramah. It has the effect of giving classes in the same package as the class in question access to the member variable or method declared with default access. Hal ini memiliki pengaruh pemberian kelas dalam paket yang sama sebagai kelas dalam akses pertanyaan ke variabel anggota atau metode dideklarasikan dengan akses default. To give a member variable or method default access, you simply don't use an access modifier, like this: Untuk memberikan sebuah variabel anggota atau metode akses default, anda hanya tidak menggunakan modifier akses, seperti ini:
class A { kelas A {In this example code, k and h take on the specific access modifiers they are declared with, and i and j assume default, or package, access. Dalam contoh kode ini, k dan h mengambil pengubah akses khusus mereka dinyatakan dengan, dan i dan j menganggap default, atau paket, akses. To convert friendly C++ code to Java, you should be able to combine friend classes together in the same package and declare many of their shared members with default access. Untuk mengkonversi ramah C + + kode ke Jawa, Anda harus dapat menggabungkan kelas-kelas teman bersama dalam paket yang sama dan menyatakan banyak dari anggota mereka bersama dengan akses default.
public int k; public int k;
private int h; private int h;
int i, j; int i, j;
} }
Booleans Boolean
In C++, there is no real boolean type; boolean values (true and false) are usually implemented as integers, with zero being interpreted as false and nonzero being interpreted as true. Dalam C + +, tidak ada jenis boolean nyata; nilai boolean (true dan false) biasanya diimplementasikan sebagai bilangan bulat, dengan nol yang diinterpretasikan sebagai palsu dan tidak nol yang diinterpretasikan sebagai benar. This usage resulted in somewhat of a half-hearted attempt by C/C++ programmers to use booleans in their code. Penggunaan ini mengakibatkan sedikit dari upaya setengah hati oleh C / C + + programmer untuk menggunakan boolean dalam kode mereka. Take a look at this example: Lihatlah contoh ini:if (--numLives) jika (- numLives)There are a couple of assumptions being made here that don't sit well from a purist programming perspective. Ada beberapa asumsi yang dibuat di sini yang tidak duduk baik dari perspektif pemrograman murni. First, if statements should always be based on a boolean value. Pertama, jika laporan harus selalu didasarkan pada nilai boolean. However, as this example shows, programmers often exploit the fact that C/C++ if statements (and other conditional statements) operate on values either being zero or nonzero, rather than true or false. Namun, seperti contoh ini menunjukkan, programmer sering mengeksploitasi fakta bahwa C / C + + jika pernyataan (dan pernyataan bersyarat lainnya) beroperasi pada nilai-nilai yang baik nol atau nol, bukan benar atau salah. The isDead variable, which clearly has a boolean meaning, uses 1 to represent true. Variabel isDead, yang jelas memiliki makna boolean, menggunakan 1 untuk mewakili benar.
isDead = 1; isDead = 1;
Unlike C/C++, Java supports boolean values as a type all their own. Tidak seperti C / C + +, Java mendukung nilai boolean sebagai tipe semua mereka sendiri. As a matter of fact, this example wouldn't work in Java because Java if statements fully expect boolean types, not integers parading as booleans. Sebagai soal fakta, contoh ini tidak akan bekerja di Jawa karena Jawa jika mengharapkan laporan penuh tipe boolean, bukan bilangan bulat memamerkan sebagai boolean. The Java version would look like this: Versi Java akan terlihat seperti ini:
if (--numLives <= 0) if (- numLives <= 0)The if statement has been changed to result in a boolean outcome. Pernyataan jika telah diubah untuk menghasilkan hasil boolean. This outcome was implied in the C++ code, but it is made clearer and more consistent in the Java version. Hasil ini tersirat di C + + kode, tetapi dibuat lebih jelas dan lebih konsisten dalam versi Jawa. The isDead variable has been changed to a boolean type. Variabel isDead telah diubah ke jenis boolean. Notice that true and false are legitimate Java keywords (as is null ). Perhatikan bahwa benar dan salah adalah sah Jawa kata kunci (seperti null).
isDead = true; isDead = true;
Most C/C++ code contains this "integer as boolean" approach and will therefore have to be fixed in a Java port. Kebanyakan C / C + + kode berisi ini "integer sebagai boolean" pendekatan dan karena itu harus tetap di pelabuhan Jawa. However, these changes are pretty simple and shouldn't take too much time. Namun, perubahan ini cukup sederhana dan tidak harus mengambil waktu terlalu banyak.

Tidak ada komentar:
Posting Komentar