advanced class features 1

50
Advanced Class Advanced Class Features 1 Features 1 Pertemuan 10 Pertemuan 10 Pemrograman Berbasis Obyek Pemrograman Berbasis Obyek Oleh Oleh Tita Karlita Tita Karlita

Upload: fidella-lerato

Post on 02-Jan-2016

45 views

Category:

Documents


1 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Advanced Class Features 1

Advanced Class Advanced Class Features 1Features 1

Advanced Class Advanced Class Features 1Features 1

Pertemuan 10Pertemuan 10Pemrograman Berbasis ObyekPemrograman Berbasis Obyek

OlehOlehTita KarlitaTita Karlita

Page 2: Advanced Class Features 1

Topik• Object class• String• StringBuffer• Math class• Wrapper class• Static • Static initializer• Final

Page 3: Advanced Class Features 1

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

Page 4: Advanced Class Features 1

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()

Page 5: Advanced Class Features 1

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 comparisonif (d1.equals(d2))

Page 6: Advanced Class Features 1

MyDate.java

Page 7: Advanced Class Features 1

TestEquals.java

Page 8: Advanced Class Features 1

MyDate.java overide method equals()

Page 9: Advanced Class Features 1

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.

Page 10: Advanced Class Features 1

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”.

Page 11: Advanced Class Features 1

Identical literals1. String s1 = “Compare me”;2. String s2 = “Compare me”;3. if (s1.equals(s2)) {4. // whatever5. }

1. String s1 = “Compare me”;2. String s2 = “Compare me”;3. if (s1 == s2)) {4. // whatever5. }

• Kedua potongan program diatas OK• Contoh pertama membandingkan contentnya.• Contoh kedua membandingkan referencesnya.

Page 12: Advanced Class Features 1

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().

Page 13: Advanced Class Features 1

equals() dan == untuk String

• Method equals() membandingkan content-nya

• == membandingkan alamatnya.

Page 14: Advanced Class Features 1

Variabel java1 dieksekusi pada saat runtime

Page 15: Advanced Class Features 1
Page 16: Advanced Class Features 1

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.

Page 17: Advanced Class Features 1

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.

Page 18: Advanced Class Features 1

• 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.

Page 19: Advanced Class Features 1

• 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.

Page 20: Advanced Class Features 1

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”

Page 21: Advanced Class Features 1

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

Page 22: Advanced Class Features 1

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.

Page 23: Advanced Class Features 1

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”

Page 24: Advanced Class Features 1

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();

Page 25: Advanced Class Features 1

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

Page 26: Advanced Class Features 1

Methods of the Math Class

Page 27: Advanced Class Features 1
Page 28: Advanced Class Features 1

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.

Page 29: Advanced Class Features 1

Primitives and Wrappers

Page 30: Advanced Class Features 1

Wrapper class• Illegal

Vector vec = new Vector();boolean boo = false;vec.add(boo); // Illegal

Page 31: Advanced Class Features 1

Wrapper class• Solution

Vector vec = new Vector();boolean boo = false;Boolean wrapper = new Boolean(boo);vec.add(wrapper); // Legal

Page 32: Advanced Class Features 1

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);

Page 33: Advanced Class Features 1

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. }

Page 34: Advanced Class Features 1

equals() dan == pada wrapper class

• Method equals() membandingkan content-nya• == membandingkan alamatnya.

Page 35: Advanced Class Features 1
Page 36: Advanced Class Features 1

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()

Page 37: Advanced Class Features 1

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.

Page 38: Advanced Class Features 1

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).

Page 39: Advanced Class Features 1

Class VariableClass 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.

Page 40: Advanced Class Features 1

Class Variable

Tanpa membuat obyeknya terlebih dahulu, kita bisa mengakses class variable dari luar class (bila variabel tersebut bertipe public)

Page 41: Advanced Class Features 1

Class MethodTanpa membuat obyeknya terlebih dahulu, kita bisa mengakses class method dari luar class.

Page 42: Advanced Class Features 1

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.

Page 43: Advanced Class Features 1

Error !!

pulic class Count{ public int serialNumber; // non-static private static int counter = 0;

public static int getSerialNumber() {return serialNumber; // compile

error}

}

Page 44: Advanced Class Features 1

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).

Page 45: Advanced Class Features 1

Contohpublic 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

Page 46: Advanced Class Features 1

Contohpublic 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

Page 47: Advanced Class Features 1

Static Initializer

Kode pada baris 4, menggunakan static method pada class Integer yang returns Integer Object.

Jalankan eksekusi aplikasi diatas dengan menggunakan command line.

Page 48: Advanced Class Features 1

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.

Page 49: Advanced Class Features 1

Final

Page 50: Advanced Class Features 1

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); // Illegal10. w1.weight = 1800; // Legal11. }12. }