Java – Class and Objects.

mahadev_k

Mahadev K

Posted on December 4, 2021

Java – Class and Objects.

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

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

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

Element

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

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

The “Vibranium”.

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;
    }


}

Enter fullscreen mode Exit fullscreen mode
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 !!
         */

    }

}

Enter fullscreen mode Exit fullscreen mode

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

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

Jarvis.createElement(vibranium);//Will have to ask Tony stark for the Jarvis services 🤷‍♂️.
Enter fullscreen mode Exit fullscreen mode

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 logo mahadev-k / JavaSeries

A Java exploration repository 🚀🚀🚀.

JavaSeries

A Java exploration repository 🚀🚀🚀.

#Run and Execute

  • Import JavaSeries as an existing project from your intellij idea/eclipse
  • Execute main class in the main package or oopMain in the oop package to see the results.
  • This project is made with Java-17 though not any Java-17 features are used.

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.

public void setAtomicMass(Integer atomicMass){
        //Variable 'atomicMass' is assigned to itself
        atomicMass = atomicMass;
        this.atomicMass = atomicMass;
    }
Enter fullscreen mode Exit fullscreen mode

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.


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

Enter fullscreen mode Exit fullscreen mode

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 🙌🙌🙌🙌

💖 💪 🙅 🚩
mahadev_k
Mahadev K

Posted on December 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related