In this video, Doug Winnie explains how to create a private member in a class using the private statement. This creates permissions and rules for the various members of your custom classes.
- [Instructor] When we create members in our class, we can define them as either being public or private. Private members are only available within the class. Let's open up our cat class and take a look at an example. In our cat class, we have a public string for the name. We can also create an integer for the age of the cat. But age isn't something you can force a change on. I can't tell a cat, hey, grow up a couple a years.
By having it as public though, that's exactly what's going on. I'm providing public access to the property. In this case, I need to make it private because I don't want to let anyone outside of the class have the ability to change the value. So I change public to private. But now I have another problem. I have a private member but now that also means that no one can get the cat's age. The solution is to create a new method that will be public and return the cat's age. So at the bottom, let's create a public method that will return an integer and we'll call it get age.
Inside, we can return the age property. Now, we can test these new permissions we have put on the cat. Go back to the main dot Java file. At the bottom, let's try and access the age property. When you enter this in, you'll get an error because in this context, the age property doesn't exist. It is private so we don't have access to it. We do have access to the get age method however.
So, let's create a new message in the console. Inside we can create a string and get the cat's age. Now build and run this program. Because we're using the public method, we're able to get the private property's value. But we have been able to secure the permissions to access the age to avoid public access to the value. You can make any member of the class private, including methods. If you want to have a method that you can only access within a class, you would type it as private.
- The history of Java
- Setting up your development environment
- Working with values and variables
- Using methods and functions
- Capturing user input
- Creating conditional tests
- Using loops
- Creating and changing arrays
- Object-oriented programming in Java
- Defining permissions
- Extending classes