Objects in Java

Objects are instance of a class. An object is created from class.

Sometimes, we need to access codes from one class to another class. Also we may need to access non static methods or variables. In those cases, objects comes in use.

In java, we have new keyword to create objects.
Syntax:

<classname> <objectname> = new <classname>();

If you remember taking input, we import Scanner class first and then create an object of a Scanner class. Then we use object to access different methods in Scanner class.

To access class elements, we use dot . between object and element.
Syntax:

<objectname>.<element>


Examples:

Lets see an example where we created object of same class and accessed non static element.
Code:

public class LearnObject { int x = 5; public static void main(String[] args) { //creating object LearnObject val = new LearnObject(); //accessing by object System.out.println(val.x); } }
Output:
5


Lets see another example where we accessed non static method.
Code:

public class LearnObject { public static void main(String[] args) { LearnObject val = new LearnObject(); val.display(); } void display() { System.out.println("I am from display."); } }
Output:
I am from display.


We can also pass parameters for method through object.
Code:

public class LearnObject { public static void main(String[] args) { LearnObject val = new LearnObject(); val.add(3,7); val.sub(8,3); } void add(int x, int y) { int z = x + y; System.out.println("Sum: " + z); } void sub(int x, int y) { int z = x - y; System.out.println("Diff: " + z); } }
Output:
Sum: 10
Diff: 5


Or we can store result in variables.
Code:

public class LearnObject { public static void main(String[] args) { LearnObject val = new LearnObject(); int sum = val.add(3,7); int diff = val.sub(8,3); System.out.println("Sum: " + sum); System.out.println("Diff: " + diff); } int add(int x, int y) { return x + y; } int sub(int x, int y) { return x - y; } }
Output:
Sum: 10
Diff: 5


At last, lets see an example where we will access method from another class. We will have also take input from user and pass that value with object to method.
Code:

import java.util.Scanner; public class LearnObject { public static void main(String[] args) { Scanner inp = new Scanner(System.in); SecondClass val = new SecondClass(); System.out.println("Enter any digit for table: "); int num = inp.nextInt(); val.table(num); } } class SecondClass { void table(int x) { for(int i = 1; i <= 10; i++) { System.out.println(x + " X " + i + " = " + x*i); } } }
Output:
Enter any digit for table:
4
4 X 1 = 4
4 X 2 = 8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
4 X 9 = 36
4 X 10 = 40


Access Modifiers in Java Previous Next Encapsulation in Java