Skip to content

Classes

A blueprint for objects

  • Lesson
  • 2 min read
  • 2 of 9 in this chapter

What is a class?

A class is a specific set of instructions(or blueprint) for creating an object. Classes can contain attributes, methods, or specific commands. These classes can then be used to make objects. Different objects can be created from a class.

For example, if we want to make a cat object, we would use the ‘Cat’ class.

How to declare a class

Making a class has 4 main parts. Modifier(public, private, or protected), a meaningful class name with the first letter capitalized, the name of the parent class(if it has one) separated by the word extend, and the code of a class surrounded by ‘{}’. For example...

Java
class Classname {
 //code goes here
}

How to create an object

You create an object by using the java keyword new. For example if we want to create a cat object we would do this...

Java
class Cat{
 //write cat code here
}
public class MyFirstClass {
 public static void main(String[] args) {
 Cat garfield = new Cat();//this is how we create an object
 }
}

Attributes

An attribute defines the property of an object. These attributes are of different data types that we learned earlier. For example...

Java
class Cat{
 //these are attributes
 String name = "Garfield";
 String color = "orange";
 String type = "tabby";
 int age = 40;
}

Constructors

A constructor initializes the state of an object, it is used to pass initial information about a class on to an object. Constructors usually have parameters to give specialized information to an object. This is how we make a constructor...

Java
public class NewWorld {
 String theWorldName;
 public NewWorld(String name){
 //this is the constructor
 /*we can add parameters to a constructor
 like up top*/
 /*we can add new attributes
 specific to this constructor*/
 this.theWorldName = name;
 }
 void printname(){
 System.out.println("this world is "+theWorldName);
 }
 public static void main(String[] args){
 String worldName = "my world";
 NewWorld theNewWorld = new NewWorld(worldName);
 theNewWorld.printname();
 }

}

The output would be...

Java
this world is my world

This may seem long now, but when we want to initialize objects with specific attributes this comes in handy.