500 likes | 656 Views
Advanced Class Features 1. Pertemuan 10 Pemrograman Berbasis Obyek Oleh Tita Karlita. Topik. Object class String StringBuffer Math class Wrapper class Static Static initializer Final. java.lang.
E N D
Advanced Class Features 1 Pertemuan 10 Pemrograman Berbasis Obyek Oleh Tita Karlita
Topik • Object class • String • StringBuffer • Math class • Wrapper class • Static • Static initializer • Final
java.lang • Java compiler automatically imports all the classes in the java.lang package into every source file. • some of the most important classes of the java.lang package: • Object • Math • The wrapper classes • String • StringBuffer
The Object Class • Class Object adalah akar dari semua class yang ada di Java. • Deklarasi class tanpa extends, secara implisit pasti ditambahkan “extends Object”. public class Employee{ } sama dengan: public class Employee extends Object{ } • The methods: • wait() • notify() • notifyAll() • equals() • toString()
equals() public boolean equals(Object object) • Untuk class Object: Fungsi method equals() sama dengan operator ==. Yaitu untuk membandingkan reference – nya. • Override equals() so that it performs a useful comparison. • Object reference comparison if (d1 == d2) • Relevant instance variables comparison if (d1.equals(d2))
toString() public String toString() • to provide a string representation of an object’s state. • It just prints out the object’s class name, followed by a hash code. • Override toString() to provide more useful information.
The String Class • Class String berisi string yang tetap (immutable string). • Sekali intance String dibuat maka isinya tidak bisa diubah. • Memiliki beberapa konstruktor. • Common string constructors: String s1 = new String(“immutable”); String s1 = “immutable”; • Java mempunyai media penyimpanan literal string yang yang disebut “pool”. • Jika suatu literal string sudah ada di pool, Java “tidak akan membuat copy lagi”.
Identical literals 1. String s1 = “Compare me”; 2. String s2 = “Compare me”; 3. if (s1.equals(s2)) { 4. // whatever 5. } 1. String s1 = “Compare me”; 2. String s2 = “Compare me”; 3. if (s1 == s2)) { 4. // whatever 5. } • Kedua potongan program diatas OK • Contoh pertama membandingkan contentnya. • Contoh kedua membandingkan referencesnya.
Explicitly calling the String constructor String s2 = new String(“Constructed”); • Pada saat kompile “Constructed” disimpan di pool tersendiri. • Pada saat runtime statement new String() dieksekusi, “Constructed” akan dibuatkan lagi di program space. • Bila di pool sudah ada “Constructed”, akan tetap dibuatkan program space. • Supaya “Constructed” benar-benar disimpan di pool maka gunakan method intern().
equals() dan == untuk String • Method equals() membandingkan content-nya • == membandingkan alamatnya.
String methods • char charAt(int index): Returns the indexed character of a string, where the index of the initial character is 0. • String concat(String addThis): Returns a new string consisting of the old string followed by addThis. • int compareTo(String otherString): Performs a lexical comparison; returns an int that is less than 0 if the current string is less than otherString, equal to 0 if the strings are identical, and greater than 0 if the current string is greater than otherString. • boolean endsWith(String suffix): Returns true if the current string ends with suffix; otherwise returns false.
String methods • boolean equals(Object ob): Returns true if ob instanceof String and the string encapsulated by ob matches the string encapsulated by the executing object. • boolean equalsIgnoreCase(String s): Creates a new string with the same value as the executing object, but in lower case. • int indexOf(int ch): Returns the index within the current string of the first occurrence of ch. Alternative forms return the index of a string and begin searching from a specified offset. • int lastIndexOf(int ch): Returns the index within the current string of the last occurrence of ch. Alternative forms return the index of a string and end searching at a specified offset from the end of the string.
int length(): Returns the number of characters in the current string. • String replace(char oldChar, char newChar): Returns a new string, generated by replacing every occurrence of oldChar with newChar. • boolean startsWith(String prefix): Returns true if the current string begins with prefix; otherwise returns false. Alternate forms begin searching from a specified offset. • String substring(int startIndex): Returns the substring, beginning at startIndex of the current string and extending to the end of the current string. An alternate form specifies starting and ending offsets. • String toLowerCase(): Creates a new string with the same value as the executing object, but in lower case.
String toString(): Returns the executing object. • String toUpperCase(): Converts the executing object to uppercase and returns a new string. • String trim(): Returns the string that results from removing whitespace characters from the beginning and ending of the current string.
Trimming and replacing 1. String s = “ 5 + 4 = 20”; 2. s = s.trim(); // “5 + 4 = 20” 3. s = s.replace(‘+’, ‘x’); // “5 x 4 = 20”
The StringBuffer Class • represents a string that can be dynamically modified. • Constructors: • StringBuffer(): Constructs an empty string buffer • StringBuffer(int capacity): Constructs an empty string buffer with the specified initial capacity • StringBuffer(String initialString): Constructs a string buffer that initially contains the specified string
StringBuffer methods • StringBuffer append(String str): Appends str to the current string buffer. Alternative forms support appending primitives and character arrays; these are converted to strings before appending. • StringBuffer append(Object obj): Calls toString() on obj and appends the result to the current string buffer. • StringBuffer insert(int offset, String str): Inserts str into the current string buffer at position offset. There are numerous alternative forms. • StringBuffer reverse(): Reverses the characters of the current string buffer. • StringBuffer setCharAt(int offset, char newChar): Replaces the character at position offset with newChar. • StringBuffer setLength(int newLength): Sets the length of the string buffer to newLength. If newLength is less than the current length, the string is truncated. If newLength is greater than the current length, the string is padded with null characters.
Modifying a string buffer 1. StringBuffer sbuf = new StringBuffer(“12345”); 2. sbuf.reverse(); // “54321” 3. sbuf.insert(3, “aaa”); // “543aaa21” 4. sbuf.append(“zzz”); // “543aaa21zzz”
String Concatenation the Easy Way • concat() method of the String class • append() method of the StringBuffer class • + operator. • Example: String Concatenation: a + b + c Java compiler treats as: new StringBuffer().append(a).append(b).append(c).toString();
The Math Class • a collection of methods and two constants that support mathematical computation. • Two constans: E dan PI • is final, so you cannot extend it. • constructor is private, so you cannot create an instance. • the methods and constants are static
The Wrapper Classes • is simply a class that encapsulates a single, immutable value. • Integer class wraps up an int value, • Float class wraps up a float value.
Wrapper class • Illegal Vector vec = new Vector(); boolean boo = false; vec.add(boo); // Illegal
Wrapper class • Solution Vector vec = new Vector(); boolean boo = false; Boolean wrapper = new Boolean(boo); vec.add(wrapper); // Legal
wrapper classes 1. boolean primitiveBoolean = true; 2. Boolean wrappedBoolean = 3. new Boolean(primitiveBoolean); 4. 5. byte primitiveByte = 41; 6. Byte wrappedByte = new Byte(primitiveByte); 7. 8. char primitiveChar = ‘M’; 9. Character wrappedChar = new Character(primitiveChar); 10. 11. short primitiveShort = 31313; 12. Short wrappedShort = new Short(primitiveShort); 13. 14. int primitiveInt = 12345678; 15. Integer wrappedInt = new Integer(primitiveInt); 16. 17. long primitiveLong = 12345678987654321L; 18. Long wrappedLong = new Long(primitiveLong); 19. 20. float primitiveFloat = 1.11f; 21. Float wrappedFloat = new Float(primitiveFloat); 22. 23. double primitiveDouble = 1.11111111; 24. Double wrappedDouble = 25. new Double(primitiveDouble);
NumberFormatException 1. Boolean wrappedBoolean = new Boolean(“True”); 2. try { 3. Byte wrappedByte = new Byte(“41”); 4. Short wrappedShort = new Short(“31313”); 5. Integer wrappedInt = new Integer(“12345678”); 6. Long wrappedLong = new Long(“12345678987654321”); 7. Float wrappedFloat = new Float(“1.11f”); 8. Double wrappedDouble = new Double(“1.11111111”); 9. } 10. catch (NumberFormatException e) { 11. System.out.println(“Bad Number Format”); 12. }
equals() dan == pada wrapper class • Method equals() membandingkan content-nya • == membandingkan alamatnya.
The retrieval methods • public byte byteValue() • public short shortValue() • public int intValue() • public long longValue() • public float floatValue() • public double doubleValue() • public boolean booleanValue() • public char charValue()
Summarize the primitive wrapper classes: • Tiap tipe data primitif mempunyai korespondensi dengan satu tipe wrapper class. • Semua tipe wrapper class dapat dibuat dari tipe data primitifnya, khusus untuk wrapper class Character bisa dibuat dari char(primitif) dan string. • Wrapped values can be tested for equality with the equals() method. • All six numeric wrapper types support all six numeric XXXValue() methods. • Wrapped values can be extracted with various XXXValue() methods. • Wrapped values cannot be modified.
Static • Static digunakan sebagai modifier pada: • Variable • Method • Inner class • Static mengindikasikan bahwa atribut atau method tersebut milik class. • Anggota class yang bersifat static ini sering disebut dengan “class members” (class variable dan class methods).
Class Variable Class variable bersifat milik bersama dalam arti semua instance/obyek dari class yang sama akan mempunyai class variable milik bersama. Class variable mirip dengan global variable.
Class Variable Tanpa membuat obyeknya terlebih dahulu, kita bisa mengakses class variable dari luar class (bila variabel tersebut bertipe public)
Class Method Tanpa membuat obyeknya terlebih dahulu, kita bisa mengakses class method dari luar class.
Static: Inggat !! • Static method bisa diakses dari luar class tanpa harus membuat obyeknya terlebih dahulu. • Konsekuensi: semua variabel atau method yang diakses oleh static method tersebut harus bersifat static juga. • Jika static method mengakses non-static method dan non-static variable maka akan menyebabkan compile error.
Error !! pulic class Count{ public int serialNumber; // non-static private static int counter = 0; public static int getSerialNumber() { return serialNumber; // compile error } }
Static Initializer • Block yang dideklarasikan static pada suatu class yang letaknya tidak berada dalam deklarasi method. • Static block ini dieksekusi hanya sekali, yaitu ketika class dipanggil pertama kali. • Jika pada statement class terdapat lebih dari satu static initializer maka urutan eksekusi berdasarkan mana yang dideklarasikan lebih dulu. • Static block biasanya digunakan untuk menginisialisasi static attribute (class variable).
Contoh public class Static2{ static{ x = 5; } static int x,y; public static void main(String args[]){ x--; myMethod(); System.out.println(x + y + x); } public static void myMethod(){ y = x + x; } } Hasil: 16
Contoh public class Static{ static{ int x = 5; } static int x,y; public static void main(String args[]){ x--; myMethod(); System.out.println(x + y + ++x); } public static void myMethod(){ y = x++ + ++x; } } Hasil : 3
Static Initializer Kode pada baris 4, menggunakan static method pada class Integer yang returns Integer Object. Jalankan eksekusi aplikasi diatas dengan menggunakan command line.
Final • Final class tidak bisa dibuat subclass. (java.lang.String merupakan final class) • Final method tidak bisa di override. • Final variable bersifat konstan. • Final variable hanya bisa dideklarasikan sekali saja, assignment final variable tidak harus pada saat dideklarasikan “blank final variable”. • Blank final instance variable harus di set di tiap constructor. • Blank final variable pada method harus di set pada method body sebelum digunakan.
Final pada variabel : Object • Referensi/alamat harus tetap, state dari object boleh dirubah 1. class Walrus { 2. int weight; 3. Walrus(int w) { weight = w; } 4. } 5. 6. class Tester { 7. final Walrus w1 = new Walrus(1500); 8. void test() { 9. w1 = new Walrus(1400); // Illegal 10. w1.weight = 1800; // Legal 11. } 12. }