Wednesday, September 2, 2015

How to access private variables and passing parameters to methods in java !

Hello ,

we're gonna talk briefly then show an example.

You won't get a job working with java if you set your variables public. So we need to set it private.

then how are we going to access it in other classes if its private?

we simply make 2 methods. First method is to allow us to set the variable.

The second method is to return it.

proving in this example how to receive an input from user by importing the "java.util.scanner" library as shown.


here is the example:-
import java.util.Scanner;

public class Fun {

public static void main(String args[]){

Scanner input = new Scanner(System.in);

milk object = new milk(); // creating an object from the class

System.out.println("enter a course name ");

String nameOfCourse = input.nextLine(); //recieving an input

object.setCourseName(nameOfCourse); // setting it

object.getCourseName(); // getting it and using it

System.out.println();

object.displayMessage(); // using the other method to display it


}

}


and we have to create that class "milk " in its seperate file but it has to get the extension such as " milk.java".

here's the class :-


public class milk {

private String courseName; // private variable






public void setCourseName(String x){ // accessing it

courseName = x;




}


public String getCourseName(){ // this method returns String data type

return courseName;



}


public void displayMessage(){ // displaying the msg

System.out.printf("welcome to %s", getCourseName());

}

} // end class







 // thank you
// next we are going to talk about constructors

1 comment: