Constructor overloading

4
Constructor overloading Siti Halisah 0857201000464

description

Constructor overloading. Siti Halisah 0857201000464. - PowerPoint PPT Presentation

Transcript of Constructor overloading

Page 1: Constructor overloading

Constructor overloading

Siti Halisah0857201000464

Page 2: Constructor overloading

Konstruktor digunakan untuk menetapkan nilai awal untuk variabel instance dari kelas. Sebuah default constructor tanpa argumen akan dipanggil secara otomatis oleh Java Virtual Machine (JVM). Konstruktor selalu disebut oleh operator baru. Konstruktor dideklarasikan seperti setelah kami menyatakan metode, kecuali bahwa constructor tidak memiliki tipe kembali. Konstruktor dapat kelebihan beban asalkan mereka harus memiliki argumen yang berbeda karena JVM membedakan konstruktor atas dasar argumen berlalu dalam constructor. Setiap kali kita memberikan nama metode yang sama seperti nama kelas. Ingat metode ini tidak harus memiliki tipe kembali. Ini disebut sebagai konstruktor overloading. Kami telah membuat satu program pada constructor overloading, setelah melalui itu konsep overloading constructor akan mendapatkan lebih jelas. Pada contoh di bawah kami telah membuat tiga konstruktor kelebihan beban masing-masing memiliki argumen yang berbeda jenis sehingga JVM dapat membedakan antara berbagai konstruktor.

Page 3: Constructor overloading

Kode program ini diberikan di bawah ini:• public class ConstructorOverloading {

public static void main ( String args []){ Rectangle rectangle1= new Rectangle ( 2 , 4 ) ; int areaInFirstConstructor=rectangle1.first () ; System.out.println ( " The area of a rectangle in first constructor is : " + areaInFirstConstructor ) ; Rectangle rectangle2= new Rectangle ( 5 ) ; int areaInSecondConstructor=rectangle2.second () ; System.out.println ( " The area of a rectangle in first constructor is : " + areaInSecondConstructor ) ; Rectangle rectangle3= new Rectangle ( 2.0f ) ; float areaInThirdConstructor=rectangle3.third () ; System.out.println ( " The area of a rectangle in first constructor is : " + areaInThirdConstructor ) ; Rectangle rectangle4= new Rectangle ( 3.0f , 2.0f ) ; float areaInFourthConstructor=rectangle4.fourth () ; System.out.println ( " The area of a rectangle in first constructor is : " + areaInFourthConstructor ) ; } }

Page 4: Constructor overloading

• class Rectangle { int l, b; float p, q; public Rectangle ( int x, int y ){ l = x; b = y; } public int first (){ return ( l * b ) ; } public Rectangle ( int x ){ l = x; b = x; } public int second (){ return ( l * b ) ; } public Rectangle ( float x ){ p = x; q = x; } public float third (){ return ( p * q ) ; } public Rectangle ( float x, float y ){ p = x; q = y; } public float fourth (){ return ( p * q ) ; } }