Getter and Setter in Java
Getter and Setter in Java. In this article we will look into what is a getter and setter and how to create a getter setter following step by step through the sample program that i have created below.
In order to show what is a getter and setter, i will create 2 separate class, one is the Class i name it” Dog” and the second class that i will create i name it “accessDog”. This class main function is to access the “Dog” class .
To Understand what is a getter and Setter is very important for a java Programmer.Setter and getter are use to pass on value from object to object, so it is widely use , and is very important that we fully understood the conept.
Follow the Step by Step below to understand what is a Getter and Setter in Java
- First i will create a Class name “Dog” . Note: The naming convention of all classes should start with a capital letter in Java.
- I created a few private variable for this Class “dogbreed”, “dogcolor”,”dogAge” Note : Private Variable can only exist or being access within its own Class.
- I created a “Setter” Method name “setDogBreed” this method function is to set a string value into the variable.
- .this.dogbreed = dogbreed; mean the parameter dogbreed inside the metod setDogBreed() will be assigned to the variable private String dogbreed;
- Then I created a method called getDogBreed() this method function is to return the string value from private String dogbreed;
- Now I will create a Class call “AccessDog” to access the Class “Dog”
- First and Foremost you need to import import java.util.*; to use the Scanner Function
- Declare a static String “inputBreed” that we will use later
- Create a new Scanner obeject call inputScan
- Create a new Dog object called yuanyuan
- Print out and ask your user to input the Dog Breed of Yuan Yuan
- Save the User Input value into inputBreed
- Print out the Breed of Yuan yuan via the yuanyuan.getDogBreed() inside the Dog class
- Close inputScan
public class Dog { private String dogbreed; private String dogcolor; private int dogAge; public void setDogBreed(String dogbreed){ this.dogbreed = dogbreed; } public String getDogBreed(){ return this.dogbreed; } }
package oop2; import java.util.*; public class AccessDog { static String inputBreed; public static void main(String[] args) { Scanner inputScan = new Scanner(System.in); Dog yuanyuan =new Dog(); System.out.println("Key in Yuan Yuan Breed"); inputBreed =inputScan.nextLine(); yuanyuan.setDogBreed(inputBreed); System.out.println("Yuan Yuan dog breed is " + yuanyuan.getDogBreed()); inputScan.close(); } }
Well that wraps up the article about getter and setter in Java , check out Java Equivalent of cin here
Check out the Java Library here
Leave a Reply