Skip to content

Constructor with Args

Learning Outcomes

  1. Can pass an argument to a constructor

  1. Create a new class called RockWithArgs
RockWithArgs
1
2
3
4
5
6
7
package com.ait.wk5;

public class RockWithArgs {
    public RockWithArgs(int i) {
        System.out.println("Creating Rock number " + i);
    }
}
  1. Add a new class called ConstructorWithArgs
ConstructorWithArgs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package com.ait.wk5;

public class ConstructorWithArgs {

    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            RockWithArgs rock = new RockWithArgs(i);
        }
    }
}

Creating Rock number 1
Creating Rock number 2
Creating Rock number 3
Creating Rock number 4
Creating Rock number 5


RockWithArgs.java
ConstructorWithArgs.java