A. Notes
In the Student class, we can use new Student() to create a new object, then set all values of instance variables one by one. This is also how we can create a new fish, a new book, a new car so far.
But this is not efficient if we have many instance variables.
There is a type of methods that are specialized in creating objects, these are constructors.
Constructors have exactly the same name as the class, it is always public, and can take parameters to initialize instance variables to create a new instance of object.
for example,
class Book {
private String name;
private String author;
private String genre;
private int pagenumber;
Book(String nName, String nAuthor, String nGenre, int npg){
setName(nName);
setAuthor(nAuthor);
setGenre(nGenre);
setPagenumber(npg);
}
public void setName(String newName){name=newName;}
public String getName(){return name;}
public void setAuthor(String newAuthor){author=newAuthor;}
public String getAuthor(){return author;}
public void setGenre(String newGenre){genre=newGenre;}
public String getGenre(){return genre;}
public void setPagenumber(int newpg){pagenumber=newpg;}
public int getPagenumber(){return pagenumber;}
}
class Main {
public static void main(String[] args) {
Book x = new Book("The Fault in Our Stars", "John Green", "Young Adult Fiction", 313);
System.out.println("Object x is: " + x.getName()+", "+x.getAuthor()+", "+x.getGenre()+", "+x.getPagenumber());
}
}
B. Exercise
Pick 2-3 classes from Student, Book, Fish, Car, CreditCard, Table, Room, declare a constructor that uses parameters to initialize all private instance variables.