Java – Class and Objects. 
Tags: java, programming, tutorial, beginners
Published: 2021-12-04 14:34:02

First of all thanks!!! 🥳🥳🥳 for the overwhelming response for my previous article.
https://dev.to/mahadev_k/java-a-brief-note-39hc

So then what's up for today?? This will be an article that will navigate you through some basic concepts of OOP - Class and Objects.
Imagine when you were a child and you got a new toy, for the first week you will play with the toy and after that you will start to dismantle it and some of you will turn that into infinite pieces Why??To see how the toy works may be and rest of you, you know just angry for some reason!!! 🤷‍♂️.
So today we will just dig what’s in this class and objects and I think you will get some basic data types 🔍.

![Look closely](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6sizeemrltvnpztak0l.gif)

#Basic Data types 

To understand this first we can analyze the basic representation of data. We have numbers (byte, short, int, long), numbers with decimal points (float, double), letters (char). We represent these data in the Java with the help of what we call data types the one I gave in brackets. 

In Java you can use primitive data types but it's better to use the boxed data types. Boxed data types wrap the primitive data type to an object. 

*int* -> Integer 
*long* -> Long

*Reference*
https://lastfiascorun.com/mexico/faq-what-are-boxed-types-in-java.html

#Wrap the data types

Now we will wrap some of these data types to make a meaningful new data type. 

This is very similar to the subway wrapper example. We wrapped all the veggies in the bread to form a new meaningful food and we called them wraps😋. 

One might think can we have a class inside a class. Yeah, sure in real world we have double decker burgers right and so, each layer will act as an instance of class here. 

We can leave these subway wraps and burgers here so that someone else can eat 😀. 


![Burger](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gp6g9cf4g5sxev0jeqoi.gif)

#Access Modifiers 

Access modifiers is nothing but it helps you control who can access what. In the above example we were able to access all the attributes/variables with just the “. (dot)” operator but it is not the right way as it simply states anyone can change the data or any class can change the data. This brings us to the necessity of a control over the class and variables access.

And so, we have the 4 access controls.  

**Private** -> Private will set the perimeter of access to the privately declared variables and methods to the declared class level. 

**Public** -> Public literally has no perimeter and anyone can access. 

**Protected** -> Protected variables can only be accessed in the package level or subclass (child class) level.

**Default** (no access specifier) -> Default will set the perimeter of access till the package level.

#Represent A Class 

From being foodie till now we can switch to some sci-fi. We will try to represent an element well known to those who know the “Wakanda”. 


![Wakanda](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ghp6j15bz0oswzz5msn.gif)
 
![Element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a3cpdl7x8ynbuhprxwhq.png)
 

The above class shows how an element is classified. An element has, 

_Atomic number_ - Integer 

_Element name_ - String 

_Element symbol_ ->\ String 

_Atomic mass_ -> Double 

Whenever we find a new element, we will fill all these fields with the new elements value and store the element with some reference. This can be related to filling some form and putting a tag over the form to easily pick and get to know what’s inside the form. 

![Files](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzoa12umbga0nu6dhbjw.gif)

Now we will fill out the details of the rare strong element out there, 

The “Vibranium”. 

```Java
package oop;

public class Element {

    /**
     *This variable can be accessed in the package level and the current package is oop, won't be accessible in the main package
     */
    Integer atomicNumber;

    /**
     * This variable is accessible in the class level and so to access it outside we have a get method below and to
     * change the value we have a set method too.
     **/
    private Integer atomicMass;

    /**
     * This variable is accessible anywhere even in the main package
     */
    public String elementName;

    /**
     * Currently this will be accessible only inside this package -> oop
     * This variable can also be accessed by a class which inherits this class.
     */
    protected String elementSymbol;

    public Integer getAtomicMass(){
        return this.atomicMass;
    }

    public void setAtomicMass(Integer atomicMass){
        this.atomicMass = atomicMass;
    }


}

```

```Java
package oop;

public class OopMain {

    public static void main(String[] args) {

        //vibranium holds the reference of the new memory location allocated to it
        Element vibranium = new Element();

        vibranium.atomicNumber = 22; // accessible as it is default and we are in the same package
        vibranium.elementName = String.valueOf("Vibranium"); //accessible public var
        vibranium.elementSymbol = String.valueOf("Vi"); //accessible as we are in the same package protected
        //vibranium.atomicMass = 35; not accessible as it is a private variable
        //we will use setter to set atomic mass
        vibranium.setAtomicMass(35);

        System.out.printf(
                "Element [%s] :\n" +
                        "Atomic Number : %d\n" +
                        "Atomic Mass : %d\n" +
                        "Element Symbol : %s\n"
                        ,vibranium.elementName
                        ,vibranium.atomicNumber
                        ,vibranium.getAtomicMass()
                        ,vibranium.elementSymbol
        );

        /**
         * Vibranium is supposed to be similar to titanium and so the properties are similarly provided 😀
         * This element doesn't exist !!
         */

    }

}

```

Now we have the vibranium’s data filled in and stored in a memory location. So how did that happen?? Spot the __“new”__ keyword, “new” keyword will help you create a space for your element in the heap memory and returns you the reference to the memory location.


![Iron man vibranium](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wy1mxb4wte87ehy2boif.gif)

And we have the vibranium now !!!. This time we can ask Jarvis to create the element 😎.

```Java 
Jarvis.createElement(vibranium);//Will have to ask Tony stark for the Jarvis services 🤷‍♂️.
```

**Always keep the variables private to the class and access those variables outside using getters and setters**.
This covers the idea of **Encapsulation**.

I have pushed all the code mentioned above in the github. Feel free to checkout !!! 😀

{% github mahadev-k/JavaSeries %}

#This Keyword

This keyword refers to the current instance. Whenever we want to access a variable of an object that we created with the help of class we use the reference of that object stored in a variable of type class. Similarly, if any method inside the class wants to use the reference of the current object, we can use the “this” keyword.  

```Java
public void setAtomicMass(Integer atomicMass){
        //Variable 'atomicMass' is assigned to itself
        atomicMass = atomicMass;
        this.atomicMass = atomicMass;
    }
```

#Constructor and new keyword 

As we know that an object is created with the help of “new” keyword. Once the object is created at least one constructor is called. If we didn’t define the constructor java compiler will provide a default constructor. Constructors can be used to set initial values of attributes. 

```Java 

/** 
* Constructor 
*/ 
Element(){ 
this.elementName = "Element"; 
} 

``` 


That's it for this article guys !!!. This was a bit huge  will see you all in the next article until then take care, good bye  🙌🙌🙌🙌