Sub topic 3
Methods, Objects, and Cleanup
This chapter assumes you already know Java variables, control flow, loops, and arrays from earlier chapters.
Methods: Parameters and Return Values
A method is a named block of code you can run whenever you need it. A parameter is a value the method receives. A return value is the result the method gives back.
public class Main {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = add(3, 4);
System.out.println(sum); // 7
}
}Here add takes two int parameters and returns an int. The word void means a method returns nothing.
Classes and Objects
A class is a blueprint for data plus behavior. An object is one thing built from that blueprint.
class Dog {
String name;
void speak() {
System.out.println(name + " says Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.name = "Rex";
d.speak(); // Rex says Woof!
}
}new Dog() creates an object; d is a reference to it.
Constructors and Object Initialization
A constructor is a special method that runs when an object is created. It usually sets up the object's fields. The keyword this refers to the current object, so this.name means "this object's name field."
class Dog {
String name;
Dog(String name) {
this.name = name;
}
void speak() {
System.out.println(name + " says Woof!");
}
}
// elsewhere:
// Dog d = new Dog("Rex");Inheritance: Building on Classes
Inheritance lets a class reuse the fields and methods of another class. The new class is a subclass; the one it builds on is the superclass. Use extends.
class Puppy extends Dog {
void play() {
System.out.println(name + " plays with a ball.");
}
}A Puppy has everything a Dog has, plus its own play method.
Garbage Collection
When no variable refers to an object anymore, the object is unreachable. Java's garbage collector is a background process that finds unreachable objects and frees their memory automatically. You never call delete — just drop your references and move on.
Exercise
What does the keyword void mean in a method declaration?
Show answer
The method does not return any value.
Exercise
What does new Dog("Rex") do?
Show answer
It creates a new Dog object and runs the constructor, which sets the dog's name to "Rex".
Exercise
When does an object become eligible for garbage collection?
Show answer
When no live reference to it remains anywhere in the program.