{"id":4084,"date":"2024-05-30T07:29:23","date_gmt":"2024-05-30T07:29:23","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=4084"},"modified":"2024-05-30T07:29:24","modified_gmt":"2024-05-30T07:29:24","slug":"java-object-and-classes","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/05\/30\/java-object-and-classes\/","title":{"rendered":"Java &#8211; Object and Classes"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Java Classes and Objects<\/h2>\n\n\n\n<p>Java is an Object-Oriented programming language. In Java, the\u00a0<strong>classes and objects<\/strong>\u00a0are the basic and important features of object-oriented programming system, Java supports the following fundamental\u00a0OOPs concepts\u00a0\u2013<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Classes<\/li>\n\n\n\n<li>Objects<\/li>\n\n\n\n<li>Inheritance<\/li>\n\n\n\n<li>Polymorphism<\/li>\n\n\n\n<li>Encapsulation<\/li>\n\n\n\n<li>Abstraction<\/li>\n\n\n\n<li>Instance<\/li>\n\n\n\n<li>Method<\/li>\n\n\n\n<li>Message Passing<\/li>\n<\/ul>\n\n\n\n<p>In this tutorial, we will learn about Java Classes and Objects, the creation of the classes and objects, accessing class methods, etc.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Java Classes<\/h2>\n\n\n\n<p>A\u00a0<strong>class<\/strong>\u00a0is a blueprint from which individual objects are created (or, we can say a class is a\u00a0data type\u00a0of an object type). In Java, everything is related to classes and objects. Each class has its\u00a0methods\u00a0and\u00a0attributes\u00a0that can be accessed and manipulated through the objects.<\/p>\n\n\n\n<p>For example, if you want to create a class for&nbsp;<em>students<\/em>. In that case, &#8220;<em>Student<\/em>&#8221; will be a class, and student records (like&nbsp;<em>student1<\/em>,&nbsp;<em>student2<\/em>, etc) will be objects.<\/p>\n\n\n\n<p>We can also consider that class is a factory (user-defined blueprint) to produce objects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Properties of Java Classes<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A class does not take any byte of memory.<\/li>\n\n\n\n<li>A class is just like a real-world entity, but it is not a real-world entity. It&#8217;s a blueprint where we specify the functionalities.<\/li>\n\n\n\n<li>A class contains mainly two things: Methods and Data Members.<\/li>\n\n\n\n<li>A class can also be a nested class.<\/li>\n\n\n\n<li>Classes follow all of the rules of OOPs such as inheritance, encapsulation, abstraction, etc.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Types of Java Class Variables<\/h3>\n\n\n\n<p>A class can contain any of the following variable types.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Local variables<\/strong>\u00a0\u2212 Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.<\/li>\n\n\n\n<li><strong>Instance variables<\/strong>\u00a0\u2212 Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.<\/li>\n\n\n\n<li><strong>Class variables<\/strong>\u00a0\u2212 Class variables are variables declared within a class, outside any method, with the static keyword.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Creating (Declaring) a Java Class<\/h3>\n\n\n\n<p>To create (declare) a class, you need to use\u00a0<em>access modifiers<\/em>\u00a0followed by\u00a0class\u00a0keyword and\u00a0<em>class_name<\/em>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Syntax to create a Java class<\/h3>\n\n\n\n<p>Use the below syntax to create (declare) class in Java:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>access_modifier class class_name{\n  data members;\n  constructors;\n  methods;...;}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example of a Java Class<\/h3>\n\n\n\n<p>In this example, we are creating a class &#8220;Dog&#8221;. Where, the class attributes are&nbsp;breed,&nbsp;age, and&nbsp;color. The class methods are&nbsp;setBreed(),&nbsp;setAge(),&nbsp;setColor(), and&nbsp;printDetails().<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Creating a Java classclassDog{\/\/ Declaring and initializing the attributesString breed;int age;String color;\/\/ methods to set breed, age, and color of the dogpublicvoidsetBreed(String breed){this.breed = breed;}publicvoidsetAge(int age){this.age = age;}publicvoidsetColor(String color){this.color = color;}\/\/ method to print all three valuespublicvoidprintDetails(){System.out.println(\"Dog detials:\");System.out.println(this.breed);System.out.println(this.age);System.out.println(this.color);}}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Java Objects<\/h2>\n\n\n\n<p>An&nbsp;<strong>object<\/strong>&nbsp;is a variable of the type&nbsp;<strong>class<\/strong>, it is a basic component of an object-oriented programming system. A class has the methods and data members (attributes), these methods and data members are accessed through an&nbsp;<strong>object<\/strong>. Thus, an object is an instance of a class.<\/p>\n\n\n\n<p>If we consider the real world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.<\/p>\n\n\n\n<p>If we consider a dog, then its state is &#8211; name, breed, and color, and the behavior is &#8211; barking, wagging the tail, and running.<\/p>\n\n\n\n<p>If you compare the software object with a real-world object, they have very similar characteristics. Software objects also have a state and a behavior. A software object&#8217;s state is stored in fields and behavior is shown via methods. So, in software development, methods operate on the internal state of an object, and the object-to-object communication is done via methods.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Creating (Declaring) a Java Object<\/h3>\n\n\n\n<p>As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the&nbsp;new&nbsp;keyword is used to create new objects.<\/p>\n\n\n\n<p>There are three steps when creating an object from a class \u2212<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Declaration<\/strong>\u00a0\u2212 A variable declaration with a variable name with an object type.<\/li>\n\n\n\n<li><strong>Instantiation<\/strong>\u00a0\u2212 The &#8216;new&#8217; keyword is used to create the object.<\/li>\n\n\n\n<li><strong>Initialization<\/strong>\u00a0\u2212 The &#8216;new&#8217; keyword is followed by a call to a constructor. This call initializes the new object.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Syntax to Create a Java Object<\/h3>\n\n\n\n<p>Consider the below syntax to create an object of the class in Java:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Class_name object_name =newClass_name(&#91;parameters]);<\/code><\/pre>\n\n\n\n<p>Note: parameters are optional and can be used while you&#8217;re using\u00a0constructors\u00a0in the class.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example to Create a Java Object<\/h3>\n\n\n\n<p>In this example, we are creating an object named&nbsp;obj&nbsp;of&nbsp;Dog&nbsp;class and accessing its methods.<\/p>\n\n\n\n<pre id=\"0\" class=\"wp-block-code\"><code>\/\/ Creating a Java classclassDog{\/\/ Declaring and initializing the attributesString breed;int age;String color;\/\/ methods to set breed, age, and color of the dogpublicvoidsetBreed(String breed){this.breed = breed;}publicvoidsetAge(int age){this.age = age;}publicvoidsetColor(String color){this.color = color;}\/\/ method to print all three valuespublicvoidprintDetails(){System.out.println(\"Dog detials:\");System.out.println(this.breed);System.out.println(this.age);System.out.println(this.color);}}publicclassMain{publicstaticvoidmain(String&#91;] args){\/\/ Creating an object of the class DogDog obj =newDog();\/\/ setting the attributes\n    obj.setBreed(\"Golden Retriever\");\n    obj.setAge(2);\n    obj.setColor(\"Golden\");\/\/ Printing values\n    obj.printDetails();}}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>Dog detials:\nGolden Retriever\n2\nGolden\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Accessing Instance Variables and Methods<\/h2>\n\n\n\n<p>Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/* First create an object *\/ObjectReference=newConstructor();\/* Now call a variable as follows *\/ObjectReference.variableName;\/* Now you can call a class method as follows *\/ObjectReference.MethodName();<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<p>In this example, We&#8217;ve created a class named Puppy. In Puppy class constructor, puppy name is printed so that when the object is created, its name is printed. An instance variable puppyAge is added and using getter\/setter method, we can manipulate the age. In main method, an object is created using new operator. Age is updated using setAge() method and using getAge(), the age is printed.<\/p>\n\n\n\n<pre id=\"1\" class=\"wp-block-code\"><code>publicclassPuppy{int puppyAge;publicPuppy(String name){\/\/ This constructor has one parameter, &lt;i&gt;name&lt;\/i&gt;.System.out.println(\"Name chosen is :\"+ name );}publicvoidsetAge(int age ){\n      puppyAge = age;}publicintgetAge(){System.out.println(\"Puppy's age is :\"+ puppyAge );return puppyAge;}publicstaticvoidmain(String&#91;]args){\/* Object creation *\/Puppy myPuppy =newPuppy(\"tommy\");\/* Call class method to set puppy's age *\/\n      myPuppy.setAge(2);\/* Call another class method to get puppy's age *\/\n      myPuppy.getAge();\/* You can access instance variable as follows as well *\/System.out.println(\"Variable Value :\"+ myPuppy.puppyAge );}}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<p>If we compile and run the above program, then it will produce the following result \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Name chosen is :tommy\nPuppy's age is :2\nVariable Value :2\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Rules for using the Classes and Objects Concepts<\/h2>\n\n\n\n<p>Let&#8217;s now look into the source file declaration rules (to use the Java classes &amp; objects approach). These rules are essential when declaring classes, import statements, and package statements in a source file.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>There can be only one public class per source file.<\/li>\n\n\n\n<li>A source file can have multiple non-public classes.<\/li>\n\n\n\n<li>The public class name should be the name of the source file as well which should be appended by\u00a0<strong>.java<\/strong>\u00a0at the end. For example \u2212 the class name is\u00a0<em>public class Employee{}<\/em>\u00a0then the source file should be as Employee.java.<\/li>\n\n\n\n<li>If the class is defined inside a package, then the package statement should be the first statement in the source file.<\/li>\n\n\n\n<li>If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file.<\/li>\n\n\n\n<li>Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and\/or package statements to different classes in the source file.<\/li>\n<\/ul>\n\n\n\n<p>Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be explaining about all these in the access modifiers chapter.<\/p>\n\n\n\n<p>Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">More Examples on Java Classes and Objects<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Example 1<\/h3>\n\n\n\n<p>The Employee class has four instance variables &#8211; name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>importjava.io.*;publicclassEmployee{String name;int age;String designation;double salary;\/\/ This is the constructor of the class EmployeepublicEmployee(String name){this.name = name;}\/\/ Assign the age of the Employee  to the variable age.publicvoidempAge(int empAge){\n      age = empAge;}\/* Assign the designation to the variable designation.*\/publicvoidempDesignation(String empDesig){\n      designation = empDesig;}\/* Assign the salary to the variable\tsalary.*\/publicvoidempSalary(double empSalary){\n      salary = empSalary;}\/* Print the Employee details *\/publicvoidprintEmployee(){System.out.println(\"Name:\"+ name );System.out.println(\"Age:\"+ age );System.out.println(\"Designation:\"+ designation );System.out.println(\"Salary:\"+ salary);}}<\/code><\/pre>\n\n\n\n<p>As mentioned previously in this tutorial, processing starts from the main method. Therefore, in order for us to run this Employee class there should be a main method and objects should be created. We will be creating a separate class for these tasks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 2<\/h3>\n\n\n\n<p>Following is the&nbsp;<em>EmployeeTest<\/em>&nbsp;class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.<\/p>\n\n\n\n<p>Save the following code in EmployeeTest.java file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>importjava.io.*;publicclassEmployeeTest{publicstaticvoidmain(String args&#91;]){\/* Create two objects using constructor *\/Employee empOne =newEmployee(\"James Smith\");Employee empTwo =newEmployee(\"Mary Anne\");\/\/ Invoking methods for each object created\n      empOne.empAge(26);\n      empOne.empDesignation(\"Senior Software Engineer\");\n      empOne.empSalary(1000);\n      empOne.printEmployee();\n\n      empTwo.empAge(21);\n      empTwo.empDesignation(\"Software Engineer\");\n      empTwo.empSalary(500);\n      empTwo.printEmployee();}}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<p>Now, compile both the classes and then run&nbsp;<em>EmployeeTest<\/em>&nbsp;to see the result as follows \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>C:\\&gt; javac Employee.java\nC:\\&gt; javac EmployeeTest.java\nC:\\&gt; java EmployeeTest\nName:James Smith\nAge:26\nDesignation:Senior Software Engineer\nSalary:1000.0\nName:Mary Anne\nAge:21\nDesignation:Software Engineer\nSalary:500.0\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Java Classes and Objects Java is an Object-Oriented programming language. In Java, the\u00a0classes and objects\u00a0are the basic and important features of object-oriented programming system, Java supports the following fundamental\u00a0OOPs concepts\u00a0\u2013 In this tutorial, we will learn about Java Classes and Objects, the creation of the classes and objects, accessing class methods, etc. Java Classes A\u00a0class\u00a0is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[263],"tags":[],"class_list":["post-4084","post","type-post","status-publish","format-standard","hentry","category-02-java-oops"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/4084","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=4084"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/4084\/revisions"}],"predecessor-version":[{"id":4085,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/4084\/revisions\/4085"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=4084"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=4084"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=4084"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}