How To Make New Class in Java (Making A Simple Mammal Class)


Classes are super important in Java and most other Object-orientated programing languages. But what exactly is a Class?

Classes Explained Simply

  • Something used to describe an object
  • Basically a blue-print

If you want to make a Dog in Java. You obviously need a way of describing this thing to the computer. You can’t put a dog in your CD drive so you need to provide some sort of logical representation. The easiest way to do this is to make a Mammal class.

You could make an animal class, but fish don’t have legs and butterfly’s aren’t describe the same way dogs are.

What to put in a class

  • Descriptions
  • Operations (methods)

Lets say we make a mammal class. We know there are certain attributes applicable only to mammals.

  • Fur colour
  • Amount of legs
  • Gender
  • Species

And other similar things. We’ll throw a name in too.

Example Mammal Class

You can see the Class is called Mammal. Mammals (in my world) have a name, fur colour, legs and a gender. So, there are variable spaces for that.

The constructor basically sets these variables when you use parameters.

Related:  HackThis: Basic+ Level 1 Solution

Making a new Object with Class

Earlier I was talking about a dog. So we’re going to make a dog.

To do this we need a main method where we call the Mammal class and make it.

It should return something like “Stinky is a Turquoise Pearlescent with Orange Hints dog with 3 legs.

You can manipulate that object. Generally you should use getters and setter methods. This will be discussed somewhere in the future-potentially-past dependent on when you’re reading this wonderful article