The amazing Java class methods and variables – J024
DeegeU Java Course
“The amazing Java class methods and variables” video is part of a larger free online class called “Free Java Course Online”. You can find more information about this class on “Free Java Course Online” syllabus.
Try at home
- Type in a program with different integer types
- Try creating errors in your program and compiling it
Transcript – The amazing Java class methods and variables
In the first lesson for classes, we talked about how we could create our own Java types. That’s awesome, but if we modeled a duck, we need a way to define more information about our duck. We might want to store the name of the duck, the color, or how much it weighs. We might even want to give our duck the ability to quack. Ducks quack right? We want an amazing duck! Let’s take a look at how you would add Java class methods and variables to our duck.
In this lesson we’ll look at how to define and use attributes in your Java classes. These attributes can belong to either the class or the object, so we’ll discus what that means and how you define it. We’ll also introduce behavior using a new concept called methods. And we’re going to revisit static final to get a better understanding what that means. By the end we should know how to create Java class methods and variables, and have our Duck class quacking!
Java class variables
Last lesson we left off with a Duck class, and the ability to create Ducks. Unfortunately our duck didn’t do much. We couldn’t even tell if it was a brown duck, or an orange duck. We just knew it was a duck.
When we’re designing applications, we often represent classes with a picture called a class diagram. We use a box with the class name at the top. We’ll use this as we add functionality to our class.
To give a class attributes, we define variables inside the scope of the class. You can think of attributes as adjectives for your class. They describe the state of your class. Attributes are listed like this in our class diagram. We separate the name and the type with a colon. This isn’t the syntax for Java though. That’s because class diagrams can apply to any object oriented programming language. In Java code, attributes are declared right after the class declaration, like this. It’s just the data type, followed by the variable name. This is the same as we saw in the variables lesson.
Now it’s tempting to add everything you can think of as an attribute, but in reality you only want to define Java class attributes that make sense for your program. You don’t want to create attributes you will never use. Remember, each attribute uses a tiny piece of memory. That adds up when you have millions of ducks. It also provides more places where your code can break. So only add what you need.
You can also use other classes as attributes. For example you might create a class called DuckTeam. It contains a list of Ducks and the team name. We’ll look at this in depth in the next lesson, but I wanted to give you a taste of the power you have with classes.
The Java dot operator
The code for setting the value uses something called the dot operator. The dot operator just allows you to access the individual attributes of a class. So if we wanted to set the weight of a individual duck, we’d set it like this. If you’re inside your class, the instance name is optional.
It’s important to have a valid object when you try to access an attribute. Otherwise you’ll get the infamous NullPointerException. You know what null is. That’s the value a class has when it’s not assigned a value. Since there’s no class assigned yet, it doesn’t know which attribute to set. Let’s look at all of this in code.
The first thing I’d like to show you is how we’d update our Duck class. Right now we don’t have any attributes. Let’s add the attributes we had in the class model. That was color, weight and age. We add those like this. Notice they are declared the same way we declared variables in the variables lesson. It’s just type, then variable name. So that’s our Duck class. Let’s instantiate a Duck in the main method of our application class.
From the last lesson, we just instantiated the class like this. If we printed out all the variables, they’d all be zero. We need to give them values. To assign a value to the attributes of our object, we use the dot operator like this. Now each has a value. We use the dot operator when we’re printing them out too. We run it, and there’s the values we set in code.
Now our application class is a class. So we can add attributes here too. Let’s create an attribute called my favorite number. We can even assign it when we declare it. When we use a variable inside the class it belongs to, we don’t need to use the dot operator. We can just use the mane. Now when we print it out in our main method, something interesting happens. It won’t let us compile. It gives the error, non static variable cannot be accessed from a static context. So what does that mean?
All of these attributes belong to the class, but are instance variables. That means each instance or object of your class has it’s own values for each attribute. That makes sense when you’re talking about the weight of a duck. Of course each duck has its own weight. But what if you wanted to keep a count of all ducks created? A variable like that would not make sense in an object. Every object would have a copy. Updating the count value in every duck could become quite onerous.
Static Java variables
There is a way to attach a attribute to the entire class. To do this, you define the attribute with the keyword static. We’d add our duckCount variable to the class, and it is available to every duck object. However it’s stored only once in memory. This attribute is called a static variable. The value belongs to the class, not an object. If you change it, you change it for all objects. To represent it in our class diagram, we underline static variables.
Instance variables are the default, and have no keyword. Class variables require the static keyword. We also usually call it with the classname in front like this. You can call a static method using the instance variable name, but that gets confusing to other developers. It’s not clear this is a static variable. So by convention, always use the class name like this.
The other use for static variables are constants. If you remember in the variables lesson, we used the keywords static final. Now you have a better idea what these keywords mean. static means it belongs to the class, and final means it never changes once set. So a static final variable is a single constant value.
This might make more sense by showing you the code.
In our Duck class we have three instance variables. These are the ones that get copied for every object. Let’s create a static variable. We’ll create the count variable. So we write static long count. That makes this variable a class variable. There is only one count for all instances. Create a million ducks, and you’ll only have one.
To show the difference, I’ll create a second duck, and I’ll initialize the second duck with different values. We’ll set count equal to 1 when we create the first duck, and then set it to 2 when we create the second duck. Notice I use the class name when I’m referencing the count. This is by convention. It makes the code easier to read, but we could also change it to be the instance variable. Before I run it, I’ll use the instance variable. I’m doing this because I want to show you that count is the same variable for both objects. Let’s run it and see what it prints.
As you can see the instance values for each duck are as we defined them, but the count is 2 in both cases. The reason is we set count to 1, and then before we printed it, we set it to two.
When we tried to create a myFavoriteNumber variable on our application eariler, it gave us the non static variable error. That was because we never created an instance of our application class. The myFavoriteNumber was an instance variable. If we add static to our definition, it will work.
Java methods
The next thing I promised was to make our duck quack. A really cool characteristic of Java classes is we can assign behavior. Our classes get behavior with Java methods. A Java method is a special Java block inside a Java class that can return a value. We also have the ability to send parameters to our methods. If classes are nouns, and attributes are adjectives, then methods are your verbs. These are the things your class can do. Methods are responsible for changing the state of your class or program.
A method has a return type, name, parameter list, and the block of code to run. The return type in this example is the keyword void. Void is another special word that means nothing. When you declare a method with a return type of void, that means it doesn’t have a return value. We’ll add the methods under the attributes. Methods always are in the second section of the class diagram box, they include the return type, and attribute list. When we execute a method, we often say we are “calling” the method. This is how we call the method in Java. It’s the variable with the dot operator again, but in this case we also list the parameters inside parentheses – even if the parameter list is empty.
In our duck example, let’s create a method called quack. It prints quack. Ok. That’s pretty boring, but that’s what ducks say.
Let’s create a more interesting method. Let’s create a method that changes the weight of our duck. In this case we send the weight as a parameter to our method. It still returns nothing, but we are passing input variables into our method. We declare parameters the same way we declare variables. So our setWeight method looks like this. Inside we change the weight attribute to the weight parameter passed in.
To get the weight back out of our class, we would introduce a method that can output a value. So let’s define getWeight. In this case our return variable is not null. It’s double, just like the weight we defined earlier. We have no parameters in this case, so we use two empty parentheses. When we define a method that returns a value, it must always return a value. Java throws an error otherwise. This also means every path through your code must return a variable. If there is a path through your code that doesn’t return a value, Java will complain. Let’s play with this in code.
To demonstrate methods we’re going to create getters and setters for our Duck. These will get and set the weight. There are many reasons why you should use getters and setters to access attributes. We’re not quite ready discuss that, but the general idea is we can separate the attribute from the behavior of getting and setting the attribute. We’ll cover it more when we discuss access modifiers. Right now, just know it’s a good thing to do.
First we’ll create a setter. This will set the value of our duck weight. Since this variable is used inside the class, we do not use the instance name. There really isn’t an instance name to use here. We assign weight to newWeight.
One of the benefits of creating getters and setters is we can do other things when we set the value. You only want to do things that make sense for these methods. Any additional action should be related to the setting of the weight. I’m going to print out a message that the weight was set.
Next we’ll create the getter. This will return our duck weight. The difference in this method is we have a return value, double, and we return a value. Nothing is passed into the method. We’ll add a message to print out here too.
Now we’ll use our new methods in the main application class. We run it, and not only does it print the correct values, we can see the messages we added.
For methods that return a value, all paths in the code must return a value. For example let’s put a conditional in the getter. We’ll say if our weight is greater than 20, we won’t return a weight. Now it won’t compile. That’s because if the weight is greater than 20, this method has no return value. It’s easy to see here in this simple code, but if you have a more complex method, it can be hard to find a missing return. Lesson learned, keep your methods simple.
Static Java methods
The last thing to do is similar to what we did with myFavoriteVariable. We’re going to create a second method on our application class. We’ll call it sayHello(). When we try to call it in our main method, we get an error again. Non static method cannot be referenced from a static context. It’s the same problem we had with myFavoriteNumber. The method belongs to the instance of the class. We’re trying to call it from the class.
One way to solve this problem is to create an instance of the application class. Then we can use the object to call the method.
We just saw that methods apply to the instance of the class. What if we wanted a method that belonged to the class? We saw this eariler with our attributes. If we want a class method instead of an instance method, we use the static keyword again. A static method applies to the class as a whole, not the instances. It also means a static method cannot access instance attributes. That’s why we got an exception when we tried accessing an instance variable from the main method. The main method is static. It can only access static variables.
Again we always use the class name in front of the method name. Let’s look at this in code.
We had our sayHello() method eariler. The way we got it to run, was to create an instance to call it from. The other way is to make the method static. That’s what we did with myFavoriteNumber earlier. We can make the method static, then call it using the class.
Note that you cannot access instance variables from a static method. Our main method is static. The reason for that is you need a place for your application to start, and there are no objects in existence yet. So main is static. That means you cannot access instance variables in your main method until you create an object.
OK, that was a big lesson. Feel free to watch it again. In this lesson we learned how to add Java class methods and variables. We looked at how we can define our methods and variables to be a part of the instance or class using the keyword static. We revisited static final from the variables lesson, and we now have a better understanding why static final creates constants in Java.
If you have any questions, please leave them on DeegeU.com or in the comments below.
Tools Used
- Java
- NetBeans
Media Credits
All media created and owned by DJ Spiess unless listed below.
- Background image from Pixabay.com
Get the code
The complete video lesson list for this free online programming course can be found on the course syllabus page.
The source code for “How to override a method in Java” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:
git clone https://github.com/deege/deegeu-java-intro.git
Go to the Support > Getting the Code page for more help.
If you find any errors in the code, feel free to let me know or issue a pull request in Git.
Don’t miss another video!
New videos come out every week. Make sure you subscribe!
Comments
DJ Spiess
Your personal instructor
My name is DJ Spiess and I’m a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I’ve programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I’ve worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.