Java Class Example

Java Class Example

Following is a class with a private variable some data of type int (integer), you can store numerical values in integer type variables. A constructor (Method with the name of the class and no return type) is also created in the class to initialize (give initial values to) variable someData. To get and set the value of variable someData outside the class using instance you must use the getter, and setter methods. As the variable is private so, it can not be accessed outside this class. To change the value of the variable public method setData() is used. In its parameters, we set the new value for the variable. Use public access modifier for getter and setter, to access the value of the variable someData.

Class for the main method:

To access public members of SomeClass.java, we create instance / object of class SomeClass by

classObj1 is the instance / object of the class SomeClass, which will be used to access public members of class SomeClass. by using setter(setData()) we set 1111 and 2222 as the values of integer someData. And to display these values, we will use showData(). By calling the showData method will display the values assigned to the variable through two different instances.

Output:

Java Class Example
Java Class Example

Leave a Reply

Your email address will not be published. Required fields are marked *