Taller class design in java
domoper94Trabajo22 de Julio de 2019
798 Palabras (4 Páginas)222 Visitas
Taller Class Design in Java Ing. Matilde Montealegre Madero, MSc. Julio 10/19
Exercise 1. Constructors
package classdesign2019;
class Dog1 {
private String color;
public Dog1(String color) {
System.out.println("constructor");
this.color = color;
// A .What happened if the line this.color = color is
changed to color = color
}
public void printColor() {
System.out.println("color= " + color);
}
// B. What happened if next line is uncommented
// public dog() {}
// public void Dog() {} // not constructor since it has
return type
}
class Cat {
private String color;
private int height;
private int length;
public Cat(int length, int theHeight) {
// length = this.length;
this.length = length;
height = theHeight;
}
public void printInfo() {
System.out.println("Cat length= " + this.length + "
height= " + height + " color= " + color);
}
}
public class ClassConstructors {
public static void main(String[] args) {
//C. Given the classes above create and instance of
class Dog1 that assign a color to a Dog and prints its
color.
//D. Create a white Cat with length 10 and height 12,
print the assignment
}
}
Exercise 2. Order of Initialization
//A. What is the order of initialization of following
code (explain)
package classdesign2019;
class Example {
private String name = "dog";
//private String name;
{
System.out.println(name);
}
private static int COUNT = 0;
static {System.out.println(COUNT);}
{
COUNT += 10;
System.out.println(COUNT);
}
public Example() {
System.out.println("constructor");
}
}
class Demo {
static {
add(2);
}
static void add(int number) {
System.out.print(number + " ");
}
Demo() {//constructor
add(5);
}
static {
add(4);
}
{
add(6);
}
//B. What if this code gets uncommented
// static {
// new Demo();
// }
{
add(8);
}
}
public class OrderOfInitialization {
public static void main(String[] args) {
new Example();
// C. uncomment the next code
// new Demo();
}
}
Exercise 3. OverloadingConstructors
For next code, Instead of the code given use this() on
constructors to give the following output
constructor 3
constructor 2
constructor 1
Jimmy husky 30.0
constructor 3
constructor 2
Anthony shepard 30.0
constructor 3
Rex german shepard 40.0
...