CanCode lesson homework (Units 5, 9, 10)
public class Student {
// private attributes
private String name;
private int age;
// public attributes
public String major;
// private method
private void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
// public methods
public void setNameAndAge(String name, int age) {
this.name = name;
setAge(age);
}
public String getNameAndAge() {
return name + " (" + age + ")";
}
public static void main(String[] args) {
Student student1 = new Student();
person1.setNameAndAge("Jack", 19);
person1.major = "Biology";
System.out.println("Person 1: " + person1.getNameAndAge() + ", " + person1.major);
}
}
class Vehicle {
// methods and attributes
private String name;
public Vehicle(String name){
this.name = name;
}
public String getName(){
return name;
}
public void honk() {
System.out.println("Honk");
}
}
class Car extends Vehicle {
// methods and attributes
public Car(String name){
super(name);
}
public static void main(String[] args) {
// new car object
Car myCar = new Car("Tesla");
// Calling method
myCar.honk();
System.out.println(myCar.getName());
}
}
// hack 4 recursion
public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
public static void main(String[] args) {
int n = 10;
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}