Skip to main content

Classes and Objects

Classes and Objects | Java: Classes are custom/used data types, and Objects are instances of the data type.

Syntax:           Class:         class_name {
                                                     // statements...
                                           }
                        Oject:     class_name object_name = new class_name(); 

Here is the Code: 

  1. import java.io.*;
  2. class Main {
  3. public static void main (String[] args) {
  4. A a = new A();
  5. a.x = 1;
  6. System.out.println(a.x);
  7. B b = new B();
  8. b.y = 2;
  9. b.z = 3;
  10. System.out.println(b.y);
  11. a.c = b;
  12. System.out.println(a.c.z);
  13. }
  14. }
  15. class A {
  16.     int x;
  17.     B c;
  18. }
  19. class B {
  20.     int y;
  21.     int z;
  22. }

Output:
1
2
3

Here is the Video: