Concept Flow - Classes and objects
Define Class
Create Object
Access Object's Fields/Methods
Use Object's Data
End
This flow shows how a class is defined, then an object is created from it, and finally how we use the object's data and methods.
Jump into concepts and practice - no test required
class Dog { String name; void bark() { System.out.println(name + " says Woof!"); } } public class Main { public static void main(String[] args) { Dog myDog = new Dog(); myDog.name = "Buddy"; myDog.bark(); } }
| Step | Action | Variable/Field | Value | Output |
|---|---|---|---|---|
| 1 | Define class Dog | - | - | - |
| 2 | Create object myDog | myDog | new Dog() | - |
| 3 | Set myDog.name | myDog.name | "Buddy" | - |
| 4 | Call myDog.bark() | - | - | Buddy says Woof! |
| 5 | End of execution | - | - | - |
| Variable/Field | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| myDog | null | Dog object | Dog object | Dog object |
| myDog.name | null | null | "Buddy" | "Buddy" |
class ClassName {
// fields
// methods
}
// Create object
ClassName obj = new ClassName();
// Access fields and methods
obj.field = value;
obj.method();
Classes are blueprints; objects are instances with data.class in Java?Car in Java?new keyword followed by the class constructor with parentheses.Car myCar = new Car();. Others miss parentheses or have wrong order.new ClassName() to create objects [OK]class Dog {
String name;
void bark() {
System.out.println(name + " says Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.name = "Buddy";
dog1.bark();
}
}dog1 has its name set to "Buddy" before calling bark().name followed by " says Woof!" so it prints "Buddy says Woof!".class Person {
String name;
void setName(String name) {
name = name;
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
System.out.println(p.name);
}
}name = name; assigns the parameter to itself, not to the instance variable.this.name = name; to refer to the instance variable.Rectangle object with double the width and height of the current one?class Rectangle {
int width;
int height;
Rectangle(int w, int h) {
width = w;
height = h;
}
// Your method here
}