Constructor

 Constructor - A constructor in Java is similar to a method that is invoked when an object of the class is created. 

Not clean version:

package main;

public class Tree {
public String type;
public double height;

public Tree(String newType, double newHeight) {
type = newType;
height = newHeight;
}

public Tree(String newType) {
type = newType;
height = 1.0;
}

public Tree(double newHeitht) {
type = "Pine";
height = newHeitht;
}

public Tree() {
type = "Pine";
height = 1.0;
}
}

Clean version:
package main;

public class Tree {
public String type;
public double height;

public Tree(String newType, double newHeight) {
type = newType;
height = newHeight;
}

public Tree(String newType) {
// type = newType;
// height = 1.0;
this(newType, 1.0);
}

public Tree(double newHeitht) {
// type = "Pine";
// height = newHeitht;
this("Pine", newHeitht);
}

public Tree() {
// type = "Pine";
// height = 1.0;
this("Pine", 1.0);
}
}

*this keyword-u birinci gelmelidir, eks halda compile time xeta alacayiq. 
---------------------------------------------------------------------------------------------
menasiz kod parcasi:
    public Tree(double newHeitht) {
System.out.println("height " + newHeitht);
type = "Pine";
height = newHeitht;
// this("Pine", newHeitht);
}
---------------------------------------------------------------------------------------------
*Tricky
package main;

public class CreditCard {
String no;
double balance;

Customer owner;

public CreditCard(String no, double balance) {
this.no = no;
this.balance = balance;
}

public CreditCard(String no, double balance, Customer owner) {
this.no = no;
this.balance = balance;
this.owner = owner;
owner.setCc(this);
}

public void setOwner(Customer owner) {
this.owner = owner;
}

@Override
public String toString() {
return "CreditCard{" +
"no='" + no + '\'' +
", balance=" + balance +
'}';
}
}
package main;

public class Customer {
int id;
String name;

CreditCard cc;

public Customer(int id, String name) {
this.id = id;
this.name = name;
}

public void setCc(CreditCard cc) {
this.cc = cc;
}

@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
", cc=" + cc +
'}';
}
}
package main;

public class Main {
public static void main(String[] args) {
Customer c1 = new Customer(1, "Ahmet");
CreditCard cc1 = new CreditCard("1", 1000);
cc1.setOwner(c1);
c1.setCc(cc1);
System.out.println(c1);

// Alternatively
Customer c2 = new Customer(2, "Kemal");
CreditCard cc2 = new CreditCard("2", 2500, c2);
System.out.println(c2);
}
}

Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class