constructors

This commit is contained in:
2020-05-10 16:07:27 +02:00
parent d6f2d44eaf
commit b9c03f8207
15 changed files with 257 additions and 1 deletions

View 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);
}
}

View File

@ -0,0 +1,6 @@
# Java example
Relevant files:
- [main.java](./main.java)
- [car.java](./car.java)

View 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();
}
}