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

public class Mammal(){

//descriptions for most mammals. add more if you like.
String name;
String furColour;
int amountOfLegs;
char gender;
String species;

//constructor to make a new mammal
public Mammal(String name, String furColour, int amountOfLegs, char gender, String species){
this.name = name;
this.furColour = furColour;
this.amountOfLegs;
this.gender = gender;
this.species = species;
}

}

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.

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.

public static void main(String args[]){

//Making my dog
Mammal stinky = new Mammal("Stinky", "Turqoise Pearlescent with Orange Hints", 3, "m", "dog");

//now say something about stinky
System.out.println(stinky.name + " is a " + stinky.furColour + " " + stinky.species + " with" + stinky.amountOfLegs + " legs.");

}

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

Cya.

4 comments
  1. Pingback: Empire Market
Leave a Reply
You May Also Like

The Best CPA Networks by Earning Potential & Click-Through Rate

These are the CPA networks that have some of the highest conversion rates,…

YouTube: How to Make Money Monetizing YouTube Compilations

Copyright infringement, that’s the phrase that was likely sitting on your mind…