constructors
This commit is contained in:
23
java/constructors/Car.java
Normal file
23
java/constructors/Car.java
Normal file
@ -0,0 +1,23 @@
|
||||
public class Car {
|
||||
|
||||
// define the fields as private to prevent outside classes from accessing them
|
||||
// access restriction will be a topic in the next lesson
|
||||
private String model = "";
|
||||
private String manufacturer = "";
|
||||
|
||||
// define the constructor
|
||||
// in java a constructor is basically a function without return type named exactly like the class
|
||||
public Car(String manufacturer, String model) {
|
||||
// set manufacturer of the current object to the given manufacturer
|
||||
this.manufacturer = manufacturer;
|
||||
// set model of the current object to the given model
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
// create the method print_info()
|
||||
public void print_info() {
|
||||
System.out.println("Car Information:");
|
||||
System.out.println("- manufacturer: " + this.manufacturer);
|
||||
System.out.println("- model: " + this.model);
|
||||
}
|
||||
}
|
6
java/constructors/README.md
Normal file
6
java/constructors/README.md
Normal file
@ -0,0 +1,6 @@
|
||||
# Java example
|
||||
|
||||
Relevant files:
|
||||
|
||||
- [main.java](./main.java)
|
||||
- [car.java](./car.java)
|
14
java/constructors/main.java
Normal file
14
java/constructors/main.java
Normal file
@ -0,0 +1,14 @@
|
||||
public class main {
|
||||
public static void main(String[] args) {
|
||||
// create a new car and store it in the variable 'a'
|
||||
// the constructor requires manufacturer and model to be specified
|
||||
Car a = new Car("Benz", "Velo");
|
||||
|
||||
// do the same for a second car
|
||||
Car b = new Car("Ford", "Model T");
|
||||
|
||||
// use a function of the car class to print out the information
|
||||
a.print_info();
|
||||
b.print_info();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user