programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Java Class Attributes

Java class attributes are the variables that are bound in a class i.e., the
variables which are used to define a class are class attributes.

A class attribute defines the state of the class during program


execution. A class attribute is accessible within class methods by
default.

For example, there is a class "Student" with some data members


(variables) like roll_no, age, and name. These data members are
considered class attributes.

Creating (Declaring) Java Class Attributes


To create (declare) a class attribute, use the access modifier followed
by the data type and attribute name. It's similar to declaring a
variable.

Syntax

Use the below syntax to declare a class attribute:

access_modifier type attribute_name;

Example: Declaring Java Class Attributes

public class Dog {


String breed;
int age;
String color;

void barking() {
}

void hungry() {
}

1|Page
void sleeping() {
}
}

In above class, we've fields like breed, age, and color which are also
known as class attributes.

Accessing Java Class Attributes


To access the class attribute, you need to create an object first and
then use the dot (.) operator with the object name. Class attributes
can be also called within the class methods directly.

Syntax

Use the below syntax to access a class attribute:

object_name.attribute_name;

Example: Accessing Java Class Attributes

Consider this example, demonstrating how to access the class


attributes.

class Dog {
// Declaring and initializing the attributes
String breed = "German Shepherd";
int age = 2;
String color = "Black";
}

public class Main {


public static void main(String[] args) {
// Creating an object of the class Dog
Dog obj = new Dog();

// Accessing class attributes & printing the values


System.out.println(obj.breed);

2|Page
System.out.println(obj.age);
System.out.println(obj.color);
}
}

Output

German Shepherd
2
Black

Modifying Java Class Attributes


To modify a class attribute, access the attribute and assign a new
value using the assignment (=) operator.

Syntax

Use the below syntax to modify a class attribute:

object_name.attribute_name = new_value;

Example: Modifying Java Class Attributes

Consider this example, demonstrating how to modify the class


attributes.

class Dog {
// Declaring and initializing the attributes
String breed = "German Shepherd";
int age = 2;
String color = "Black";
}

public class Main {


public static void main(String[] args) {
// Creating an object of the class Dog
Dog obj = new Dog();

3|Page
// Accessing class attributes & printing the values
System.out.println("Before modifying:");
System.out.println(obj.breed);
System.out.println(obj.age);
System.out.println(obj.color);

// Modifying class attributes


obj.breed = "Golden Retriever";
obj.age = 3;
obj.color = "Golden";

// Printing
System.out.println("\nAfter modifying:");
System.out.println(obj.breed);
System.out.println(obj.age);
System.out.println(obj.color);
}
}

Output

Before modifying:
German Shepherd
2
Black

After modifying:
Golden Retriever
3
Golden
AD

4|Page
Making Java Class Attributes Read Only
You can also make the class attributes read-only by using
the final keyword after the access modifier while declaring an
attribute.

Syntax

Use the below syntax to make class attribute read-only:

access_modifier final data_type attribute_name;

Example: Making Java Class Attributes Read Only

In the below example, the name attribute is set to read-only using


the final keyword. Now this attribute can not be modified and JVM
will complain if we try to modify this attribute.

class Dog {
final String name = "Tommy";
}

public class Tester {


public static void main(String[] args) {
Dog dog = new Dog();
dog.name = "Tommy"; // Error while modifying name
System.out.println(dog.name);
}
}

Output

Compile and run Tester. This will produce the following result −

Exception in thread "main" java.lang.Error: Unresolved compilation problem:


The final field Dog.name cannot be assigned

Java Class Methods


5|Page
The class methods are methods that are declared within a class. They
perform specific operations and can access, modify the class
attributes.

Creating (Declaring) Java Class Methods


Class methods declaration is similar to the user-defined
methods declaration except that class methods are declared within a
class.

The class methods are declared by specifying the access


modifier followed by the return type, method_name, and parameters
list.

Syntax

Use the below syntax to declare a Java class method:

public class class_name {


modifier returnType nameOfMethod(Parameter List) {
// method body
}
}

The syntax shown above includes −

 modifier − It defines the access type of the method and it is


optional to use.
 returnType − The returns data type of the class method.
 nameOfMethod − This is the method name. The method
signature consists of the method name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and
number of parameters of a method. These are optional, method
may contain zero parameters.
 method body − The method body defines what the method does
with the statements.

Example

6|Page
Here is the source code of the above defined method
called minimum(). This method takes two parameters n1 and n2 and
returns the minimum between the two −

class Util {
/** the snippet returns the minimum between two numbers */
public int minimum(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

Accessing Java Class Methods


To access a class method (public class method), you need to create
an object first, then by using the object you can access the class
method (with the help of dot (.) operator).

Syntax

Use the below syntax to access a Java public class method:

object_name.method_name([parameters]);

Example

Following is the example to demonstrate how to define class method


and how to access it. Here, We've created an object of Util class and
call its minimum() method to get minimum value of given two numbers

class Util {
public int minimum(int n1, int n2) {

7|Page
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
public class Tester {

public static void main(String[] args) {


int a = 11;
int b = 6;

Util util = new Util();

int c = util.minimum(a, b);


System.out.println("Minimum Value = " + c);
}
}

Output

Minimum value = 6

this Keyword in Java Class Methods


this is a keyword in Java which is used as a reference to the object of
the current class, with in an instance method or a constructor.
Using this you can refer the members of a class such as constructors,
variables and methods.

Note − The keyword this is used only within instance methods or


constructors

In general, the keyword this is used to −

8|Page
 Differentiate the instance variables from local variables if they
have same names, within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}
 Call one type of constructor (parametrized constructor or
default) from other in a class. It is known as explicit constructor
invocation.
class Student {
int age
Student() {
this(20);
}

Student(int age) {
this.age = age;
}
}

Example: Using this Keyword in Java Class Methods

Here is an example that uses this keyword to access the members of


a class. Copy and paste the following program in a file with the
name, Tester.java.

public class Tester {


// Instance variable num
int num = 10;

Tester() {
System.out.println("This is an example program on keyword this");
}

Tester(int num) {

9|Page
// Invoking the default constructor
this();

// Assigning the local variable num to the instance variable num


this.num = num;
}

public void greet() {


System.out.println("Hi Welcome ");
}

public void print() {


// Local variable num
int num = 20;

// Printing the local variable


System.out.println("value of local variable num is : "+num);

// Printing the instance variable


System.out.println("value of instance variable num is : "+this.num);

// Invoking the greet method of a class


this.greet();
}

public static void main(String[] args) {


// Instantiating the class
Tester obj1 = new Tester();

// Invoking the print method


obj1.print();

// Passing a new value to the num variable through parametrized constructor


Tester obj2 = new Tester(30);

// Invoking the print method again


10 | P a g e
obj2.print();
}
}

Public Vs. Static Class Methods


There are two types of class methods public and static class method.
The public class methods are accessed through the objects whereas,
the static class methods are accessed are accesses without an object.
You can directly access the static methods.

Example

The following example demonstrates the difference between public


and static class methods:

public class Main {


// Creating a static method
static void fun1() {
System.out.println("fun1: This is a static method.");
}

// Creating a public method


public void fun2() {
System.out.println("fun2: This is a public method.");
}

// The main() method


public static void main(String[] args) {
// Accessing static method through the class
fun1();

// Creating an object of the Main class


Main obj = new Main();
// Accessing public method through the object
obj.fun2();
}

11 | P a g e
}

Output

fun1: This is a static method.


fun2: This is a public method.
AD

Java - Variable Scopes

The variable's scope refers to the region where they are created and
accessed in a given program or function. The variable scope also
refers to its lifetime.

Scope of Java Instance Variables


A variable which is declared inside a class and outside all the methods
and blocks is an instance variable. The general scope of an instance
variable is throughout the class except in static methods. The lifetime
of an instance variable is until the object stays in memory.

Example: Scope of Java Instance Variables

In the example below, we define an instance


variable puppyAge in Puppy class and using its setAge(), we're
modifying it and using getAge() method, we're getting it. This
variable is available till the lifetime of myPuppy object instance.

public class Puppy {


private int puppyAge;

public void setAge( int age ) {


// access the instance variable and modify it
puppyAge = age;
}

12 | P a g e
public int getAge( ) {
// access the instance variable
return puppyAge;
}

public static void main(String []args) {


Puppy myPuppy = new Puppy();
myPuppy.setAge( 2 );
System.out.println("Puppy Age :" + myPuppy.getAge() );
}
}

Compile and run the program. This will produce the following result

Output

Puppy Age :2

Scope of Java Local Variables


A variable which is declared inside a class, outside all the blocks and
is marked static is known as a class variable. The general scope of a
class variable is throughout the class and the lifetime of a class
variable is until the end of the program or as long as the class is
loaded in memory.

Example: Scope of Java Local Variables

In the example below, we define a class variable BREED in Puppy class.


This variable is available till the lifetime of program. Being static in
nature, we can access it using class name directly as shown below:

public class Puppy {


private int puppyAge;
public static String BREED="Bulldog";

13 | P a g e
public void setAge( int age ) {
// access the instance variable and modify it
puppyAge = age;
}

public int getAge( ) {


// access the instance variable
return puppyAge;
}

public static void main(String []args) {


Puppy myPuppy = new Puppy();
myPuppy.setAge( 2 );
System.out.println("Puppy Age :" + myPuppy.getAge() );
// access the class variable
System.out.println("Breed :" + Puppy.BREED );
}
}

Compile and run the program. This will produce the following result

Output

Puppy Age :2
Breed :Bulldog

Scope of Java Class (Static) Variables


All other variables which are not instance and class variables are
treated as local variables including the parameters in a method.
Scope of a local variable is within the block in which it is declared and
the lifetime of a local variable is until the control leaves the block in
which it is declared.

14 | P a g e
Example: Scope of Java Class (Static) Variables

In the example below, we define two local varables in main() method


of Puppy class. These variables are availble till the lifetime of
method/block in which these are declared and can be accessed as
shown below

public class Puppy {


private int puppyAge;
public static String BREED="Bulldog";

public void setAge( int age ) {


// access the instance variable and modify it
puppyAge = age;
}

public int getAge( ) {


// access the instance variable
return puppyAge;
}

public static void main(String []args) {


Puppy myPuppy = new Puppy();
myPuppy.setAge( 2 );
System.out.println("Puppy Age :" + myPuppy.getAge() );
// access the class variable
System.out.println("Breed :" + Puppy.BREED );

// local variables
int a = 10;
int b = 20;

int c = a + b;

System.out.println("c: " + c);


}

15 | P a g e
}

Compile and run the program. This will produce the following result

Output

Puppy Age :2
Breed :Bulldog
c: 30

Important Points About Variables Scope


 By default, a variable has default access. Default access modifier
means we do not explicitly declare an access modifier for a
class, field, method, etc.
 A variable or method declared without any access control
modifier is available to any other class in the same package. The
fields in an interface are implicitly public static final and the
methods in an interface are by default public.
 Java provides a number of access modifiers to set access levels
for classes, variables, methods, and constructors. The four
access levels are −
o default − Visible to the package. No modifiers are needed.
o private − Visible to the class only.
o public − Visible to the world.
o protected − Visible to the package and all subclasses.

16 | P a g e

You might also like