Java class data field

Class Data Field and Methods in Java

Computer Graphics OpenGL Mini Projects

Final Year Projects

What is a class in Java? Explain how data fields and methods are declared and accessed in Java – Java Tutorial

Problem Statement

What is a class in Java? Explain how data fields and methods are declared and accessed in Java using a programming example.

Solution:

A class can be defined as an entity in which data and functions are put together. The concept of class is similar to the concept of structure in C. A class is declared by using the keyword class.

The general form of class is

type method n(paramteter-list)

The data lies within the class and the data fields are accessed by the methods of that class.

The data fields are also called instance variables or member variables because they are created when the objects get instantiated.

For example –

In object-oriented programming, any two objects communicate with each other using methods.

All the methods have the same general form as the method main(). Most of the methods are specified as either static or public.

Java classes do not need the method main, but if you want a particular class as a starting point for your program then the main method is included in that class.

The general form of method is –

The type specifies the type of data returned from the method. If the method does not return anything then its data type must be void.

For returning the data from the method the keyword return is used.

Objects are nothing but the instances of the class. Hence a block of memory gets allocated for these instance variables.

For creating objects in Java the operator new is used.

Test obj // Declaration of object obj.

obj = new Test () ; // obj gets instantiated for class Test

We instantiate one object obj; it can be represented graphically as –

Class Data Field and Methods in Java

Now we can two objects and instantiate them,

It can be represented graphically as –

Declaring Objects

There are two types of class members – The data members and the method.

These members can be accessed using the dot operator.

For accessing the data members the syntax is –

For accessing the method of the class the syntax is

Suppose we wish to pass the parameters to the method then first we will create the object for the class as follows –

Now two objects are created namely obj1 and obj2.

Suppose by this method we assign values to two variables a and b then

It can be graphically represented as –

Accessing Variables and Methods

Sample Program to demonstrate, how to access data fields and methods

/*This is a Java program which shows the use of class in the program */ class Rectangle < int height; int width; void area() < int result=height*width; System.out.println('The area is "+result); >> //Another class in which main() function is written. class classDemo < public static void main(String args[]) < Rectangle obj=new Rectangle(); obj.height=10; //setting the attribute values obj.width=20; //from outside of class obj.area(); //using object method of class is called >>

In the above program, we have used two classes one class is classDemo which is our usual one in which the main function is defined and the other class is Rectangle.

In this class, we have used height and width as attributes and one method area() for calculating the area of a rectangle. In the main function, we have declared an object of a class as

Rectangle obj=new Rectangle();

And now using obj we have assigned the values to the attributes of a class. The operator new is used to create an object.

The objects access the data fields and methods of the class using the dot operator. This operator is also known as the object member access operator.

This data field height and width are called instance variables.

And the method, area is referred to as the instance method. The object on which the instance method is invoked is known as the calling object.

Summary:

In this article, we understood What is a class in Java? Explain how data fields and methods are declared and accessed in Java using a programming example – Java Tutorial. If you like the tutorial share it with your friends. Like the Facebook page for regular updates and the YouTube channel for video tutorials.

Источник

Java Fields

A Java field is a variable inside a class. For instance, in a class representing an employee, the Employee class might contain the following fields:

The corresponding Java class could be defined like this:

Field Declaration Syntax

A Java field is declared using the following syntax:

[access_modifier] [static] [final] type name [= initial value] ;

The square brackets [ ] around some of the keywords mean that this option is optional. Only type and name are required.

First an access modifier can be declared for a Java field. The access modifier determines which object classes that can access the field. In the Employee example above there were no access modifiers.

Second, a data type for the Java field must be assigned. In the Employee example above the data types String , int and Date were used.

Third, the Java field can be declared static . In Java, static fields belongs to the class, not instances of the class. Thus, all instances of any class will access the same static field variable. A non-static field value can be different for every object (instance) of a class.

Fourth, the Java field can be declared final or not. A final field cannot have its value changed. A final field must have an initial value assigned to it, and once set, the value cannot be changed again. A final field is often also declared static . A field declared static and final is also called a «constant».

Fifth, the Java field is given a name. You can choose this name freely, but there are some restrictions on what characters the name can contain.

Sixth, you can optionally set an initial value for the field.

Some of the above options are described in more detail in the following sections.

Java Field Access Modifiers

The Java field access modifier determines whether the field can be accessed by classes other than the the class owning the field. There are four possible access modifiers for Java fields:

The private access modifier means that only code inside the class itself can access this Java field.

The package access modifier means that only code inside the class itself, or other classes in the same package, can access the field. You don’t actually write the package modifier. By leaving out any access modifier, the access modifier defaults to package scope.

The protected access modifier is like the package modifier, except subclasses of the class can also access the field, even if the subclass is not located in the same package.

The public access modifier means that the field can be accessed by all classes in your application.

Here are a few examples of fields declared with access modifiers. The modifiers are in bold.

The above use of Java field access modifiers are for the sake of this example only. You would probably not use all access modifiers in the same class. Most often you use private and protected . For simple, data carrying classes you may declare all fields public .

The Java access modifiers are covered in more detail in my Java access modifiers tutorial.

Static and Non-static Fields

A Java field can be static or non-static.

A static field belongs to the class. Thus, no matter how many objects you create of that class, there will only exist one field located in the class, and the value of that field is the same, no matter from which object it is accessed. Here is a diagram illustrating static fields:

Static Java fields are located in the class, not in the instances of the class.
Static Java fields are located in the class, not in the instances of the class.

You define a static field by using the static keyword in the field declaration, like this:

Static fields are located in the class, so you don’t need an instance of the class to access static fields. You just write the class name in front, like this:

Customer.staticField1 = "value"; System.out.println(Customer.staticField1);

Non-static Java fields, on the other hand, are located in the instances of the class. Each instance of the class can have its own values for these fields. Here is a diagram illustrating non-static fields:

Non-static Java fields are located in the instances of the class.
Non-static Java fields are located in the instances of the class.

You define a non-static Java field simply by leaving out the static keyword. Here is an example:

To access a non-static field you need an instance of the class (an object) on which you can access it. Here is an example:

Customer customer = new Customer(); customer.field1 = "value"; System.out.println(customer.field1);

Final Fields

A Java field can be declared final . A final field cannot have its value changed, once assigned. You declare a field to be final by adding the final keyword to the field declaration. Here is an example:

The value of the field1 field cannot be changed now. That means, that even if the field belongs to objects (class instances), you cannot vary the value of the field from object to object.

When you cannot change the value of a final field anyways, in many cases it makes sense to also declare it static . That way it only exists in the class, not in every object too. Here is an example:

Since static final fields are often used as constants, the naming convention is to write the field name in all uppercase, and to separate the words with underscore _ . Here is a Java static final field example:

Naming Java Fields

The name of a Java field is used to refer to that field from your code. Here is an example:

Customer customer = new Customer(); customer.city = "New York"; System.out.println(customer.city);

The first line creates a new Customer object (an instance of the Customer class), and stores it in a variable called customer . The second line assigns the String value New York to the Customer objects city field. The third line prints out the value of the city field to the console output.

The naming restrictions and naming conventions for fields are the same as for any other type of variable.

Initial Field Value

A Java field can have be given an initial value. This value is assigned to the field when the field is created in the JVM. Static fields are created when the class is loaded. A class is loaded the first time it is referenced in your program. Non-static fields are created when the object owning them are created.

Here is an example of a Java field being declared with an initial value:

Whether you want to initialize your Java fields (and other variables) to an initial value is up to you. I have made it a habit to always initialize my variables to some sensible value, but it is just a habit. It is not necessary to do so.

Источник

Читайте также:  Приоритет мат операций python
Оцените статью