Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      Class Attributes

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      Class Attributes

      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() {
      }
      
      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);
      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();
      
      // 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

      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.
      package com.tutorialspoint;
      
      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
      
      at com.tutorialspoint.Tester.main(Tester.java:10)