Konstruktor

Sintaksis Jawa
tingkat , wulangan
kasedhiya

A snippet kuliah karo mentor minangka bagéan saka kursus Universitas Codegym. Ndaftar kanggo kursus lengkap.


"Saiki wis wektune aku pitutur marang kowe bab konstruktor. Iki konsep tenan prasaja. Programmer wis nemokke cara shorthand kanggo nggawe lan initialize obyek. "

Tanpa konstruktor Kanthi konstruktor
MyFile file = new MyFile();
file.initialize("c:\data\a.txt");
String text = file.readText();
MyFile file = new MyFile("c:\data\a.txt");
String text = file.readText();
MyFile file = new MyFile();
file.initialize("c:\data\", "a.txt");
String text = file.readText();
MyFile file = new MyFile("c:\data\", "a.txt");
String text = file.readText();
MyFile file = new MyFile();
file.initialize("c:\data\a.txt");

MyFile file2 = new MyFile();
file2.initialize( MyFile file, "a.txt");
String text = file2.readText();
MyFile file = new MyFile("c:\data\a.txt");


MyFile file2 = new MyFile(file, "a.txt");
String text = file2.readText();

"Aku wis rampung sinau babagan metode initialize ..."

"Katon harder. Kanthi konstruktor, kode luwih trep lan kompak."

"Dadi iku. Iki pitakonan. Aku ngerti carane nulis cara initialize nang kelas, nanging carane aku nulis konstruktor?"

"Pisanan, deleng conto iki:"

Tanpa konstruktor Kanthi konstruktor
class MyFile
{
  private String filename = null;

  public void initialize(String name)
  {
    this.filename = name;
  }

  public void initialize(String folder, String name)
  {
    this.filename = folder + name;
  }

  public void initialize(MyFile file, String name)
  {
    this.filename = file.getFolder() + name;
  }

…
}
class MyFile
{
  private String filename = null;

  public MyFile(String name)
  {
    this.filename = name;
  }

  public MyFile(String folder, String name)
  {
    this.filename = folder + name;
  }

  public MyFile(MyFile file, String name)
  {
    this.filename = file.getFolder() + name;
  }

…
}

"Gampang kanggo ngumumake konstruktor ing kelas. Konstruktor padha karo metode initialize , kanthi mung rong beda:

1. Jeneng konstruktor padha karo jeneng kelas (tinimbang initialize).

2. Konstruktor ora duwe jinis (ora ana jinis sing dituduhake).

"OK, dadi kaya initialize , nanging karo sawetara beda. Aku aku njaluk iku."

Komentar
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION