How to Have One Class Read Another Classes Variable Java

We discussed the concept of classes and objects in the previous chapter. Before learning to create classes and objects using Java, let'due south see one more example.

We know that a student has a proper noun and a roll number. So, we can say that Educatee is a class, and name and curl number are the attributes of this class. Furthermore, we know that in that location can be many students and each student will have a proper noun and a roll number. Thus, all students are the objects of the Student class.

And then, you must have understood the basic concept of classes and objects. Now, permit'southward see how to create a grade and its objects.


Creating Classes and Objects in Java

A form is created using the class keyword.

                        class            Student            {            String            name            ;            int            roll_no            ;            }          

In the above declaration, Educatee is the name of a course. In other words, Student is a class.

In the trunk of the class, the attributes name and roll_no are divers.

So, we can say that each student has a proper name and a roll number.

Attributes are variables defined inside a class.

At present let's create an object of this class.

                        // Student class            class            Student            {            String            name            ;            int            roll_no            ;            }            // Test (Chief) class            class            Test            {            public            static            void            primary            (            Cord            []            args            )            {            // creating object st of class Student            Student            st            =            new            Student            ();            }            }          

In the above case, Test is the main class containing the main method.

The course which has the main method within it is known every bit the primary class. Till now we were writing all our code in the main grade.

We created the Student class having two attributes - name and roll_no.

Student st = new Student() → We created an object st of the Student class. Nosotros tin can also say that st is a Student.

The terms object and instance are used interchangeably.

Any number of objects of a class can be created.

                        // Student grade            course            Student            {            String            name            ;            int            roll_no            ;            }            // Test (Main) class            grade            Test            {            public            static            void            chief            (            String            []            args            )            {            // creating objects st1 and st2 of form Student            Student            st1            =            new            Pupil            ();            Educatee            st2            =            new            Student            ();            }            }          

Hither, nosotros created ii objects of the Pupil form - st1 and st2. Thus, st1 and st2 are two Students having some name and whorl number.

You lot now know how to create a class with attributes and its objects. Now let's movement forward and assign values to attributes.


Java Attributes

Nosotros know that attributes are variables defined in a grade. They specify the features (properties) of the class. For example, name and roll_no are the attributes/features of the Student form.

                            // Student class              grade              Student              {              String              name              =              "John"              ;              }              // Test (Main) class              form              Exam              {              public              static              void              chief              (              Cord              []              args              )              {              // creating object st of class Student              Student              st              =              new              Student              ();              Organization              .              out              .              println              (              st              .              name              );              }              }            

Output

In this example, a class named Student is defined. It has an attribute name having the value "John".

Student st = new Student() → An object st of the Student class is created.

System.out.println(st.name) → The object st accesses the attribute name of the class through st.name and its value is printed.

Note that an object of a course tin can access the attributes of that class using the dot '.' operator. In the higher up case, the object st accesses the attribute name of the Student class through st.proper noun.

accessing methods using dot (.) in Java

In the above example, nosotros can say that st is a Pupil whose name is "John".

Let's see another way to assign value to attributes.

                            // Student grade              class              Pupil              {              String              name              ;              }              // Test (Main) class              course              Test              {              public              static              void              main              (              String              []              args              )              {              // creating object st of grade Student              Student              st              =              new              Student              ();              // assigning value to aspect name              st              .              name              =              "John"              ;              Organization              .              out              .              println              (              st              .              name              );              }              }            

Output

Hither, the statement st.name = "John" assigned the value of the aspect name for the object st to "John".

Look at another instance.

                                // Pupil class                class                Educatee                {                Cord                name                =                "John"                ;                }                // Exam (Primary) grade                class                Test                {                public                static                void                master                (                Cord                []                args                )                {                // creating objects st1 and st2 of form Student                Student                st1                =                new                Student                ();                Student                st2                =                new                Student                ();                System                .                out                .                println                (                "Student 1 Name: "                +                st1                .                name                );                Organization                .                out                .                println                (                "Student 2 Name: "                +                st2                .                name                );                }                }              

Output

Student 1 Name: John
Student 2 Name: John

2 objects st1 and st2 of the Student grade are created. These objects accessed the value of the attribute name through st1.name and st2.name respectively.

Thus, st1 and st2 are two Students having the same proper name i.e. "John".

Now in the above example, we can ascertain different names for both the objects as shown below.

                                // Student class                class                Educatee                {                String                name                ;                }                // Test (Main) class                class                Test                {                public                static                void                main                (                Cord                []                args                )                {                // creating objects of grade Educatee                Student                st1                =                new                Student                ();                Student                st2                =                new                Educatee                ();                // assigning values to attribute name for objects                st1                .                name                =                "John"                ;                st2                .                proper noun                =                "Julie"                ;                Organisation                .                out                .                println                (                "Pupil 1 Name: "                +                st1                .                name                );                Organization                .                out                .                println                (                "Student ii Proper noun: "                +                st2                .                name                );                }                }              

Output

Student ane Proper name: John
Educatee 2 Name: Julie

The statement st1.proper noun = "John" assigned the value of the aspect name for the object st1 as "John" and the statement st2.name = "John" assigned the value of the attribute name for the object st2 as "Julie".

Thus, st1 is a Student having the name "John" and st2 is also a Student having the proper noun "Julie".

If you lot have understood till here, the rest of the topic will be an piece of cake walk for you. Let's move further.


Coffee Methods in Class

In the to a higher place examples, we divers variables (known equally attributes) in a class. Similarly, we tin can also define methods in a form. The variables and methods defined in a grade are chosen members of the course.

Let's define a method in our Student class.

                            // Student course              course              Student              {              String              name              =              "John"              ;              void              clarification              ()              {              System              .              out              .              println              (              "This is a student"              );              }              }              // Test (Master) form              class              Test              {              public              static              void              main              (              String              []              args              )              {              // creating object st of class Educatee              Educatee              st              =              new              Student              ();              // accessing variable proper name of class              Organization              .              out              .              println              (              st              .              proper name              );              // accessing method description of class              st              .              description              ();              }              }            

Output

In this example, the Student grade has a variable (attribute) proper noun and a method description() divers in information technology. This variable and method are the members of the class.

Nosotros created an object st of this form. Thus, the object accessed the class aspect by writing st.proper noun and the class method by writing st.description().

At present let'southward look at another example.

                            class              Student              {              String              proper name              ;              void              setName              (              String              northward              )              {              name              =              n              ;              }              String              getName              ()              {              return              name              ;              }              }              class              Test              {              public              static              void              main              (              String              []              args              )              {              Student              st              =              new              Student              ();              st              .              setName              (              "John"              );              String              st_name              =              st              .              getName              ();              System              .              out              .              println              (              "Student Name: "              +              st_name              );              }              }            

Output

We created the Pupil class having an attribute name and methods getName() and setName().

Student st = new Student() → An object st of the course is created.

st.setName("John") → The object st calls the method setName() past passing "John" to it. Inside the setName() method, name = n assigns "John" to the variable name.

Cord st_name = st.getName() → The object st calls the method getName(). Inside the getName() method, render proper name returns the value of the variable proper name i.east. "John". Thus, the value of the variable st_name becomes "John".

By now, you know how to create classes and its objects. You also know that variables and methods tin can be defined in a class and can exist accessed by the objects of that class. Pretty uncomplicated uptil here, right?

At present allow's movement onto the side by side concept.


Java Constructor

A constructor is a special form method which gets called automatically whenever an object of the class is created. Its proper name is the same as the class name and it has no render type.

Constructor is a special type of method which is used to initialize an object. Information technology is invoked at the fourth dimension of object creation.

Since the constructor is called at the time of object creation, the role of the code that yous want to execute at the time of object creation should be written in information technology.

An example will help understand the use of a constructor.

                                class                Pupil                {                String                name                ;                // constructor                Pupil                ()                {                name                =                "Unknown"                ;                }                void                setName                (                String                n                )                {                name                =                n                ;                }                Cord                getName                ()                {                return                proper name                ;                }                }                form                Test                {                public                static                void                chief                (                String                []                args                )                {                // creating object st of Student grade                Pupil                st                =                new                Student                ();                // press value of name of st                System                .                out                .                println                (                "Student Name: "                +                st                .                getName                ());                // changing value of name of st                st                .                setName                (                "John"                );                // press value of name of st                Organization                .                out                .                println                (                "Pupil Name: "                +                st                .                getName                ());                }                }              

Output

Pupil Name: Unknown
Student Name: John

In this instance, the Educatee class is defined with an attribute proper noun, a constructor Student() and two methods getName() (returns the value of proper noun) and setName() (assigns a value to proper noun).

When we created the object st of the form Student, the constructor Student() automatically got chosen. Within the constructor, the value of the attribute name is initialized to "Unknown". Therefore, on printing the value of st.getName() after that, "Unknown" got printed.

Next, st.setName("John") chosen the setName() method to set the value of name to "John". Thus, on printing the value of st.getName() after that, "John" got printed.

Therefore, in the higher up example, nosotros are assigning the name of the objects as "Unknown" by default using the constructor.

Let'southward encounter another example.

                                form                Student                {                String                name                ;                int                historic period                ;                // constructor                Pupil                ()                {                name                =                "Unknown"                ;                age                =                0                ;                }                void                setDetails                (                String                n                ,                int                a                )                {                name                =                north                ;                historic period                =                a                ;                }                void                printDetails                ()                {                System                .                out                .                println                (                "My name is "                +                name                +                " and my age is "                +                age                );                }                }                grade                Examination                {                public                static                void                main                (                String                []                args                )                {                Student                st1                =                new                Student                ();                Educatee                st2                =                new                Student                ();                st1                .                setDetails                (                "John"                ,                25                );                st2                .                setDetails                (                "Julie"                ,                20                );                st1                .                printDetails                ();                st2                .                printDetails                ();                }                }              

Output

My proper name is John and my age is 25
My proper name is Julie and my age is xx

Yous must have understood this program. When the objects st1 and st2 were created, the constructor Student() got called and assigned name every bit "Unknown" and historic period equally 0 for both the objects. Later on that, both the objects called the setDetails() method to gear up the corresponding values of name and historic period and the printDetails() method to impress their values.

Nosotros can also make a constructor with nothing in its body.

Student(){ };

If we don't explicitly create whatsoever constructor in a class, and so the compiler automatically creates a constructor with no parameter and empty torso.

Java Constructor Having Parameters

We can besides define constructors having parameters.

                                class                Student                {                String                name                ;                int                historic period                ;                // constructor                Educatee                (                String                north                ,                int                a                )                {                proper noun                =                n                ;                age                =                a                ;                }                void                printDetails                ()                {                Arrangement                .                out                .                println                (                "My name is "                +                name                +                " and my age is "                +                age                );                }                }                class                Test                {                public                static                void                master                (                String                []                args                )                {                Student                st1                =                new                Student                (                "John"                ,                25                );                Pupil                st2                =                new                Educatee                (                "Julie"                ,                xx                );                st1                .                printDetails                ();                st2                .                printDetails                ();                }                }              

Output

My name is John and my age is 25
My proper noun is Julie and my age is xx

Here, the constructor Educatee() has two parameters, the commencement parameter of type String and the second parameter of type int. Therefore, when creating an object of the Student class, nosotros have to laissez passer two arguments.

Expect at the following argument.

Pupil st1 = new Student("John", 25);

This statement creates an object st1 and calls the Student() constructor past assigning the value "John" to n and 25 to a. In the constructor, n ("John") is assigned to proper noun and a (25) is assigned to age. The same is done for the object st2 likewise.

Using public and private Modifiers

We will discuss modifiers in the chapter Access Modifiers. Let's just learn most a few things which are necessary for now. Members (variables and methods) of a class are usually alleged as private or public.

Declaring a course variable/method as private means that the variable/method can be accessed only inside the class. Accessing a private variable/method outside the class will issue in an error. Whereas, declaring a grade variable/method every bit public means that the variable/method can be accessed exterior the class in which it is defined.

Therefore, we can't admission a individual variable/method through the grade object outside the class.

Usually, class variables (attributes) are declared private and class methods are alleged public. (We will acquire about the reason for doing so in the Encapsulation chapter)

Allow's make all class variables as individual and class methods equally public in the final example.

                                class                Student                {                private                String                name                ;                private                int                age                ;                // constructor                public                Student                (                String                n                ,                int                a                )                {                name                =                n                ;                age                =                a                ;                }                public                void                printDetails                ()                {                System                .                out                .                println                (                "My name is "                +                proper name                +                " and my age is "                +                age                );                }                }                class                Test                {                public                static                void                principal                (                String                []                args                )                {                Pupil                st1                =                new                Student                (                "John"                ,                25                );                st1                .                printDetails                ();                }                }              

Output

My proper noun is John and my age is 25

In this example, the object st1 was able to access the method printDetails() considering this method is alleged as public.

Now allow's try to access a private attribute outside the class in the above example.

                                course                Student                {                private                String                name                ;                private                int                age                ;                // constructor                public                Student                (                String                n                ,                int                a                )                {                name                =                north                ;                age                =                a                ;                }                public                void                printDetails                ()                {                Organisation                .                out                .                println                (                "My proper noun is "                +                name                +                " and my age is "                +                age                );                }                }                grade                Test                {                public                static                void                chief                (                String                []                args                )                {                Student                st1                =                new                Student                (                "John"                ,                25                );                Organisation                .                out                .                println                (                st1                .                proper name                );                }                }              

Output

Examination.java:19: error: name has private access in Pupil
System.out.println(st1.name);                                 ^
1 error

We got an error. This is because the object st1 tried to access the individual attribute name outside the Educatee class.

From now on, let's make a habit of declaring class attributes as private and class methods every bit public in normal weather. In the rest of the examples, we will follow this design.

Let's see another example.

                            grade              Rectangle              {              private              int              length              ;              private              int              breadth              ;              public              Rectangle              (              int              l              ,              int              b              )              {              length              =              50              ;              breadth              =              b              ;              }              public              int              getArea              ()              {              return              length              *              breadth              ;              }              }              form              Test              {              public              static              void              main              (              Cord              []              args              )              {              Rectangle              rect              =              new              Rectangle              (              2              ,              four              );              System              .              out              .              println              (              rect              .              getArea              ());              }              }            

Output

This plan has a class named Rectangle which has length and breadth equally attributes and a method getArea() that returns the surface area of the rectangle. Try to empathise the rest of the code yourself.


Coffee static

Declaring a variable/method divers in a course as static ways that the variable/method can be accessed without making an object of the class in which information technology is defined. In other words, static is used and then that we can access any variable or method in a class without making an object of that grade.

Let'due south understand with an instance.

                        class            Rectangle            {            public            static            void            printArea            (            int            l            ,            int            b            )            {            System            .            out            .            println            (            l            *            b            );            }            }            course            Exam            {            public            static            void            main            (            String            []            args            )            {            Rectangle            .            printArea            (            2            ,            iv            );            }            }          

Hither, the method printArea() is declared every bit static. As a outcome, we were able to access it by directly using the class name Rectangle, without creating an object of the course.

Now permit'due south get to the last topic of this chapter.


Returning and passing object in a method

Yes, we tin return or laissez passer object(s) to a method.

Let's see how.

                            form              Business relationship              {              public              int              balance              ;              public              Account              ()              {              balance              =              0              ;              }              public              static              Account              getAcc              (              Business relationship              a              ,              Account              b              )              {              Business relationship              air conditioning              =              new              Account              ();              ac              .              residuum              =              a              .              balance              +              b              .              rest              ;              return              ac              ;              }              }              class              Examination              {              public              static              void              principal              (              String              []              args              )              {              Account              a1              =              new              Business relationship              ();              a1              .              rest              =              50              ;              Business relationship              a2              =              new              Business relationship              ();              a2              .              balance              =              sixty              ;              Account              a3              =              Account              .              getAcc              (              a1              ,              a2              );              Organisation              .              out              .              println              (              a3              .              balance              );              }              }            

Output

In this example, the getAcc() method is taking two Business relationship objects as parameters and returning an Business relationship object. Note that the attribute balance is defined as public considering nosotros want the objects to straight admission this aspect in this example.

Account a3 = Account.getAcc(a1, a2);

In the above statement, the getAcc() method is taking the objects a1 and a2 and is returning a new object of the Account course. The returned object is assigned to a3.

                        public            static            Account            getAcc            (            Account            a            ,            Account            b            )            {            Account            ac            =            new            Account            ();            ac            .            balance            =            a            .            residue            +            b            .            rest            ;            render            ac            ;            }          

Inside the getAcc method, a new object ac is created. And so the sum of balances of the two parameter objects is assigned to the residue of ac, and finally ac is returned.

Then this completes the topic - classes and objects. If you have understood this chapter, then you take surpassed many beginners who find information technology difficult.

This might be a heavy chapter, then go through it thoroughly and ask doubts in the discussion forum. Besides practice questions on classes and objects from the practice section earlier moving onto the adjacent affiliate.

If You Are Working On Something That You Really Intendance About, You lot Don't Have To Be Pushed. The Vision Pulls Y'all.

- Steve Jobs


mooreasibliver.blogspot.com

Source: https://www.codesdope.com/course/java-classes-and-objects/

0 Response to "How to Have One Class Read Another Classes Variable Java"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel