-2

I've recently gotten started learning Java, and I have a question regarding a code structure that I've found frequently in some textbooks. This is a simplified version of what I've found, but I am mainly interested in the usage of the ForMe instance.

Firstly, what exactly is the use of this instance? Why do we need to create it, and why can't we just include the code in the class body? Also, is this structure considered to be a class instance (an object)? Secondly, why does it work to compile the code, considering that ForMe is not declared as public/static/etc? I apologize if these questions are stupid, I am new to coding and I'm just trying to properly understand OOP

sori
  • 1
  • 1

1 Answers1

0

Object Oriented Programming is an interesting aspect of programming. It is confusing at first but with time it just gets easier and easier when you begin to apply it in your codes.

I'd try to answer your questions.

Firstly, what exactly is the use of this instance?

An instance (also called object) of a class is like an offspring of a class, so whatever is declared in the ForMe class can only be accessed by an instance (offspring) of ForMe.

But sometimes the ForMe class can say "Hey, I don't want my kids to have this variable. I want it to be mine only"

So ForMe class can declare a variable, method, inner class, inner interface as static, meaning the variable, method etc is for the class and not for any of its objects.

Why do we need to create it

You need to create an instance of a class to be able to access the properties defined in the class. For example in the ForMe class, the number int variable and the array int [ ] variable can only be accessed by an instance (offspring) of the ForMe class.

So you may need to do something like this to access the int[ ]:

ForMe mine = new ForMe();
int[] a = mine.array;
System.out.println(Arrays.toString(a));

It would print - [1,2,3,4,5,6,7,8,9,10]

So you need an instance of a Class to access the properties defined in that class.

This encompasses the concept of Data Encapsulation where you create a Data class (a class whose sole aim is to store data) and make all the declared variables private, then you define accessor and mutator methods (getters and setters) to modify and access the stored data.

These accessor and mutator methods would then only be available to an object (offspring) of a class.

Secondly, why does it work to compile the code, considering that ForMe is not declared as public/static/etc?

NOTE: if you do not explicitly define a visibility modifier (public, private, protected etc) on a class, then that class is given the default visibility modifier by Java which is the package private. This means the class is only visible and accessible to classes defined in the same package. Check this Stack overflow post for further explanations.

Alright, I hope this was helpful.

IODevBlue
  • 71
  • 4