PROGRAMMING

MINTE9
REMEMBERS




Last update:   23-07-2021

Constructor

p241 ! Every class you create has a constructor, even if you don't write one. Constructor use the class name and has no return type.
 RunCode
class LearningApp {
    public static void main(String[] args) {
        Output o = new Output("a");
        o.Output("b");
    }
}

class Output{

    public Output(String s) { 

        // constructor - no return type
    }

    public void Output(String s) { 

        // method - return type
    }
}
... 8 lines
˄˄˄
p247 You could have more than one constructor in a class.
 RunCode
class LearningApp {
    public static void main(String[] args) {
        Output o1 = new Output();
        Output o2 = new Output("aaa");
        o1.Output("bbb"); // bbb
    }
}

class Output{

    public Output() { // constructor 1
    }
    
    public Output(String s) { // constructor 2
    }
    
    public void Output(String s) { // method - return type
        System.out.println(s);
    }
}
... 10 lines
˄˄˄
p256 You can use this() to call another constructor in the same class.
 RunCode
class LearningApp {
    
    private static Rectangle obj;

    public static void main(String[] args) {
        
        obj = new Rectangle(10, 20); // Look Here

        System.out.println(obj);
    }
    
}

class Rectangle {

    private int x, y;
    private int width, height;
    
    public Rectangle() {
        this(0, 0, 0, 0); // Look Here
    }
    
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public String toString() {
        return String.format("W: %s H: %s", width, height);
            // W: 10 H: 20    
    }
}
... 21 lines
˄˄˄
p254 The first statement of your constructor must be a call to superclass constructor.
 RunCode
class LearningApp {
    public static void main(String[] args) {
        Dog d = new Dog();
    }
}

class Dog extends Animal {
    public Dog() { // Error: call to super must be first statement
        String name = "Puppy";
        super();
    }
}

class Animal {
    public Animal() {
    }
}
... 9 lines
˄˄˄
Task

 CompleteTask
/**
 * Write constructor and method for Output class.
 * The output() prints the <name> instance variable
 */

class LearningApp {
    public static void main(String[] args) {
        Output o = new Output("John");
        o.output(); // John
    }
}

...

solution code
Questions    
15. Nested Classes
14 . Constructor
Last update:   23-07-2021

        A B C D E F
🔔
1/3