Introduction
A class is like a blueprint to create objects. It helps organize data and actions together.
Jump into concepts and practice - no test required
A class is like a blueprint to create objects. It helps organize data and actions together.
class ClassName { // fields (data) // methods (actions) }
The class name should start with a capital letter.
Fields store information, methods define what the class can do.
class Dog { String name; int age; }
class Car { String model; void start() { System.out.println("Car started"); } }
This program defines a Person class with name and age. It has a method to say hello. In main, it creates a Person, sets details, and calls the method.
public class Person { String name; int age; void sayHello() { System.out.println("Hello, my name is " + name + " and I am " + age + " years old."); } public static void main(String[] args) { Person p = new Person(); p.name = "Alice"; p.age = 30; p.sayHello(); } }
Remember to create objects from the class to use it.
Fields can be different types like int, String, etc.
Methods can use fields to do actions or show information.
A class is a blueprint to create objects with data and actions.
Use classes to organize and reuse code easily.
Define fields for data and methods for actions inside a class.
class Car { }Person in Java?class followed by the class name and braces.class Person { }. Others have incorrect order or keywords.class Dog {
String name = "Buddy";
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
System.out.println(d.name);
}
}class Animal {
String type;
void Animal() {
type = "Mammal";
}
}void Animal() is treated as a regular method, not a constructor, causing no constructor defined.Book with a field title and a method printTitle() that prints the title. Which code correctly implements this?title to print its value.print(title) causes an error. Only System.out.println(title) correctly prints the field value.