12.2 Declaring Classes

Declaring Classes

To declare a class in Java, use the following syntax:

modifiers class ClassName {
			// class body

Keep in mind that class names are always capitalized using camel case, except that the first letter of the first word is also capitalized. Also note that you can declare a class with different modifiers, such as public or private. (That’s why, as you may have noticed, String is capitalized while char is not — String is a class while char is a primitive type.)

For example, if I wanted to declare a public class called Person with the fields name, age, address, and hungry, I would code:

public class Person {
			// fields below
			private String name;
			private int age;
			private String address;
			private boolean hungry;
			// methods
View this code on GitHub

You should put the fields of the class inside the class body first, followed by the class’s methods. Fields are usually private while methods are usually public. This is because of the concept of encapsulation, which you can read about here


Note: You can only have 1 public class per Java file. The name of that public class must match the name of the file.


Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.