Java - OOP - Classes - Part 5 - Classes are reference type
In earlier article, we had declared a class, added member method, member method. We created instance of our object. In this article, we will be looking how instances work and what is reference type.
Lets look to syntax of creating an instance of java class.
public class Main
{
public static void main(String[] args)
{
servers s1 = new servers();
s1.hostname = "stargateDocker1";
System.out.println(s1.hostname);
}
}
Our class definition is as follows:
public class servers
{
String OStype;
String ip;
String hostname;
}
Reference type means when we create and assign an object, basicly if assigned first instance gets modified, it means 2nd instance which was referenced to it gets updated too. In memory point of view, in memory, both objects points to same memory address way.
Lets see it in Java class example.
In above example, we had 2 member field to our class "server" which contains member field: "ostype", "ip", and "hostname". In our java example, we created an instance and assigned its "hostname" member field "docker1". As that each class instance represents one server entity. Recall that the class was like business logic template.
To demonsrate reference type, we created 2nd instance as "s2" and said java "s2=s1". Notice that when we change value of "s1" instance hostname, "s2" hostname is changed too. It means both reference same address in memory.
Data Layers
Area: | programming \ languages \ java \ \ \ |
Ref: | |
Loc: | |
Tags: | java |
|