You must be curious to know What are Classes in Java? How Classes are Created? What Are Objects in Java? How Objects are created in Java? How Objects are removed from the system? Where they are stored exactly? How the Objects are really accessed and from where?
As the title say's "Demystifying Classes and Objects in Java" 😊
What is Class in Java?
A Class is a blueprint for an Object. It helps the JVM understand how to create object of that type. JVM means Java Virtual Machine this is the thing that actually runs our code.
For example on our website we have content of different coding
languages and if we want to represent it in object oriented way , we can
create a class that will have a variable called codingLanguage which will
hold the value of the coding languages on which we post topics, and we could
create objects from that class each object representing the language like
Java, Kotlin, Python.
Each Object made from the class will have its own set of values for the instance variables.
A class will have a set of variables that logically correlate with each other, for example if we create a class of type House it will not have a variable called "canWalk" right 😊 , I mean you can have it but it's not logically correct. So a class is a blueprint or logical template of an object using which the JVM can create an Object of that particular type.
Before Diving deep into Classes, let clear some basics on
Objects. I assure you it will be just basics and we will cover much more on
Objects in Java in the later part of the post.
What are Objects in Java?
So as you know classes are blueprint of an Object, and Objects are the
instance of that class i.e objects are the actual thing that will have a state
and behaviour specified in the class for that object.
For Example if we have class Person with fields like name, age etc. Then an
Object of the class will have an actual values assigned to it and will get a
place in memory and you can do all sort of operations on that object.
See more about Objects in later part of this post.
A class consists of Access Modifiers, Instance Variables, Constructors, Methods etc, don't worry we will cover all of these.
Let' see how to create a Class for the above example ,
everything in Java is made up of Class, the body of the class should be
inside curly braces.
A class should have a name (recommended to use upper case for first letter), some variables and methods to access and set those variables.
Note every Class should have a constructor. If constructor is
not specified a default constructor is created and default values are
assigned to the instance variables.
What are Access Modifiers In Java and Different Types?
Access Modifiers in Java are used to control the access to the Class and Members of the Class like variables, methods , constructors etc.
In Java we have 4 Access Modifiers
- Public
- Private
- Protected
- Default
- Public Access Modifier: If any Class or Methods or Instance Variables are declared using public modifier that means that is accessible everywhere, in all levels of package across the system. It is the least restrictive Access Modifier in Java.
- Private Access Modifier: If a Method or Instance variable are declared using private modifier then those are only accessible within the same class.
- Protected Access Modifier: Members declared using protected access modifier are accessible within the same package. Ex we have a Class A in Package "abc" then all classes that are within the package "abc" can access the protected members of the Class A. Along with all the sub classed of Class A. It doesn't matter if the Sub-Class is in different package or not.
- Default Access Modifier: Default is an access modifier which is set by Java if we don't use any Access Modifiers . The access level of members would be within the package for Default modifier.
The variables that we declare inside the class that define the state or
property of an object or the class( in case of static variables) are called
as variables of a class.
Instance variables always have a default value, if we don't assign a value
during declaration or by using setter methods then also they will have
default values.
Ex:
integers: 0
booleans: false
references: null
Ex: codingLanguage variable of the KodeSrc class above.
The variables in below code are instance variables.
class KodeSrcClassExample{
private String name;
private int score;
private Boolean isBest;
}
The functions that are defined inside the class and are used to
perform operations on the variables are called methods of a class. These
functions controls the behaviour of the class/ objects.
A method should have a return type, if nothing is expected to be returned
then make it as void.
These methods can have parameters and also return types.
Ex:
getCodingLanguage(), setCodingLanguage() methods of the class.
The functions in below code are called methods.
class KodeSrcClassExample{
private String name;
private int score;
private Boolean isBest;
public void setIsBestToTrue(){
this.isBest=true;
}
}
Different Types of Classes in Java
- Abstract Class
- Static Class
- Final Class
- Singleton Class
- Inner Class
Abstract Class In Java:
Abstract class in java are declared using abstract keyword. This class may or might not have any abstract methods in it.Abstract classes are usually extended by concrete classes (normal classes) to give a function body of abstract methods.
Abstract classes have abstract methods that needs to be
overridden in the sub class. We cannot instantiate an abstract class, in
order to make use of abstract class they should be extended.
See more about abstract class in java here. Abstract Class In Java By KodeSrc
abstract class KodeSrcAbstract
{
public void printName(){
System.out.println("KodeSrc!");
}
abstract void concatString(String s1,
String s2);
}
Static and Inner Classes In Java:
To understand Static and Inner Classes, first understand
What are nested Classes In Java?
Ans: A class that is declared inside another class is called as nested class.
Now ,
What are Inner Classes?
Ans: The Nested Class that is non static is called Inner Class. Inner class can access all members of outer class.
class A{
private int field;
class B{
private int fieldOfB;
}
}
What are Static Classes?
class A{
private int field;
static class B{
private int fieldOfB;
}
}
Final Classes In Java:
final class KodeSrcFinalClass{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Final classes cannot be inherited i.e we cannot use extends keyword for this classes.
Singleton Classes In Java:
What are Objects in Java?
Objects are instance of the class, it has a state and behaviour and represents an actual instance of a class and has a space in memory.
JVM creates objects from the class, you know right classes are blueprint
for an object using which JVM does the object creation. Objects have a
state (the variables mentioned in the class) and behaviour ( methods
declared in the class) .
Both these affects each other, yes behaviour (methods) affects the state and state also affects the behaviour, we will see it with examples later on, for now just bare with me for sometime.
How To Create Objects In Java?
public class KodeSrc {
private String codingLanguage;
public String getCodingLanguage()
{
return codingLanguage;
}
public KodeSrc(
String codingLanguage
) {
this.codingLanguage = codingLanguage;
}
public void setCodingLanguage(
String codingLanguage)
{
this.codingLanguage = codingLanguage;
}
}
public class Main {
public static void main(String[] args) {
KodeSrc kodeSrc=new KodeSrc("KodeSrc!");
System.out.println(kodeSrc.getCodingLanguage());
}
}
What is a constructor in Java?
public KodeSrc(
String codingLanguage
) {
this.codingLanguage = codingLanguage;
}
KodeSrc kodeSrc=new KodeSrc("KodeSrc!");
What is Heap storage in Java?
In Java we have 2 memory areas The Stack and The Heap. The JVM gets some memory from the operating system when it is started say 256 MB etc.
When we create objects in Java they are allocated place in the Heap area.
This heap is also termed as Garbage collectable heap and there is a garbage collector that helps in cleaning up the heap to free up the memory.
What is Stack Area ?
The other part of the memory where all method calls, local variables are kept is known as Stack.
Method are pilled up on stack during the execution , the latest method is kept at the top and once that is finished it is popped out of the stack and memory is freed.
What is a reference Variable in Java?
Reference variables are nothing but the variables that are used to access objects placed in the heap.
As objects gets memory in the heap area there has to be way to access those objects so reference variables are those which are used to access objects and control the object actions.
A good analogy I read for reference variables that you can think it as a remote control of objects.
How Objects are removed from the Heap?
The life of object totally depends upon its reference variables, if an object has a reference variable pointing to it then it will be not eligible for garbage collecting.
If an object is lonely and there is no reference that is pointing to it then that object is eligible for garbage collecting and JVM will let the GC remove that object from the heap and free up the memory.
Why Garbage collector removes object that has no reference variable pointing?
Ok, so think it in this way the objects are located in heap, right?
And the reference variables are used to access those objects, correct?
Now if there is no one pointing to that object the address of that object is lost correct. So is there any use of that Object? Will you be able to access it anyway?
No right. So GC removes that object from the heap and free the memory because that object is of no use now.
public class KodeSrc {
private String siteName;
public String getSiteName()
{
return siteName;
}
public KodeSrc(
String siteName
) {
this.siteName = siteName;
}
public void setSiteName(
String siteName)
{
this.siteName = siteName;
}
}
KodeSrc kodeSrc=new KodeSrc("KodeSrc!");
Please Let me Know, If you have any doubts.
Please Let me Know, If you have any doubts.