Introduction
Classes help you create blueprints for things. Objects are actual things made from these blueprints.
Jump into concepts and practice - no test required
Classes help you create blueprints for things. Objects are actual things made from these blueprints.
class ClassName { // fields (data) // methods (actions) } // Create an object ClassName objectName = new ClassName();
Class names start with a capital letter by convention.
Objects are created using the new keyword.
class Dog { String name; int age; void bark() { System.out.println(name + " says Woof!"); } } Dog myDog = new Dog(); myDog.name = "Buddy"; myDog.age = 3; myDog.bark();
class Light { boolean isOn; void toggle() { isOn = !isOn; System.out.println("Light is now " + (isOn ? "On" : "Off")); } } Light lamp = new Light(); lamp.toggle(); lamp.toggle();
This program defines a Car class with color and speed. It creates a Car object, sets its properties, and calls the drive method to print a message.
class Car { String color; int speed; void drive() { System.out.println("The " + color + " car is driving at " + speed + " km/h."); } } public class Main { public static void main(String[] args) { Car myCar = new Car(); myCar.color = "red"; myCar.speed = 50; myCar.drive(); } }
Fields store information about the object.
Methods define what the object can do.
You can create many objects from one class, each with its own data.
Classes are blueprints for objects.
Objects are instances of classes with their own data.
Use classes and objects to organize and reuse your code.
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
}