Java Class Attributes

Class variables are called as java attributes for class.

We can define variable by data types.

Example : 

public class Main {
  int p = 9;
  int q = 2;
}

 

As per as above example, variable p and q are called as attributes for class Main.

We can access attributes by creating an object of the class as below.

Main obj = new Main();
System.out.println(obj.p);
System.out.println(obj.q);

Example :

import java.util.*;

public class Demo {
int p =687;
public static void main(String[] args) {
Demo obj = new Demo();
System.out.println("Value for class attribute p is "+obj.p);
}
}

Output :

Value for class attribute p is 687

Comments

Leave a Reply

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

24861