Building Blocks
Objects
Creating objects
• object is an instance of the class (house → blueprint)
• new object is created using a keyword new :
Student s = new Student()
• when object is created, the constructor of the object is called
// in file [Link] the constructor
public class Student { (like method, but no return type)
public Student() {
[Link]("New student is created.");
$ java MyApp
// in file [Link]
New student is created.
public class MyApp {
public static void main(String[] args) {
Student s = new Student();
} new object is created
} and constructor is called
// will this compile?
public class Student { return type
public void Student() {
[Link]("New student is created.");
// YES!
// But here Student() is just a method, not a constructor
// (it will not be called when new object is created)
// good practice is to write methods with lowercase first letter
// (but exam creators like these kind of practical jokes)
// if you don't provide any constructor, the compiler will generate
// simple no-argument constructor: public Student() { }
// reading and modifying fields:
public class Student {
String name; // instance variable
public static void main(String[] args) {
Student s = new Student(); // creating an object
[Link] = "John Wayne"; // set variable
[Link]([Link]); // get variable
}
Order of initialization
• the code between two brackets {...} is called code block
• instance initializer - code block outside the method
• order of initialization:
1. elds and instance initializer blocks in order in which they appear
2. constructor runs in the end
fi
public class Dog {
private String name = "Chip";
public Dog() { 2
name = "Teddy";
[Link]("Inside the constructor...");
} 1
{ [Link]("Inside the initializer block..."); }
public static void main(String[] args) {
Dog dog = new Dog(); 3 $ java Dog
[Link]([Link]); Inside the initializer block...
Inside the constructor...
} Teddy