47 lines
1.2 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// housekeeping/Flower.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
// Calling constructors with "this"
public class Flower {
int petalCount = 0;
String s = "initial value";
Flower(int petals) {
petalCount = petals;
2015-12-02 09:20:27 -08:00
System.out.println(
"Constructor w/ int arg only, petalCount= "
2015-06-15 17:47:35 -07:00
+ petalCount);
}
Flower(String ss) {
2015-12-02 09:20:27 -08:00
System.out.println(
"Constructor w/ String arg only, s = " + ss);
2015-06-15 17:47:35 -07:00
s = ss;
}
Flower(String s, int petals) {
this(petals);
2015-12-18 11:28:19 -08:00
//- this(s); // Can't call two!
2015-06-15 17:47:35 -07:00
this.s = s; // Another use of "this"
2015-11-03 12:00:44 -08:00
System.out.println("String & int args");
2015-06-15 17:47:35 -07:00
}
Flower() {
this("hi", 47);
2015-11-03 12:00:44 -08:00
System.out.println("no-arg constructor");
2015-06-15 17:47:35 -07:00
}
void printPetalCount() {
2015-12-18 11:28:19 -08:00
//- this(11); // Not inside non-constructor!
2015-12-02 09:20:27 -08:00
System.out.println(
"petalCount = " + petalCount + " s = "+ s);
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
Flower x = new Flower();
x.printPetalCount();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Constructor w/ int arg only, petalCount= 47
String & int args
2015-12-15 11:47:04 -08:00
no-arg constructor
2015-06-15 17:47:35 -07:00
petalCount = 47 s = hi
2015-09-07 11:44:36 -06:00
*/