Java is an object oriented programming language which means it is composed of classes and objects and has attributes and methods. Attributes are the variables like intx, floaty and methods are the functions which takes parameters and do some operations. A class is defined using the keyword class. An object of a class is created by the name of the class followed by the object name, and keyword new. Objects are used to access the attributes and methods using the dot (.) operator.
The following program shows a class named “ClassesAndObjects” and objects obj1 and obj2.
package com.company;
public class ClassesAndObjects {
int x = 3;
int y = 5;
public static void main(String[] args) {
ClassesAndObjects obj1 = new ClassesAndObjects();
ClassesAndObjects obj2 = new ClassesAndObjects();
System.out.println(obj1.x);
System.out.println(obj2.y);
}
}
Output:
3
5
There can be multiple classes in one Java file but the Java file should be saved with the name of the class which contains the main function. The following program shows two classes in one Java file.
package com.company;
class One {
int x = 3 ;
void prt() {
System.out.println("The value of x is " +x);
}
}
class Other {
public static void main(String[] args) {
One obj = new One();
obj.prt();
}
}
Output:
The value of x is 3
Different Java class can be created in different file and can be accessed with one Java file having a class which has the main function. The name of the Java file should be same as the class name. All Java files should be in the same folder.
The following program shows two different Java classes FirstOne and SecondOne in two different files. SecondOne contains the main function and on execution it prints the output.
package com.company;
public class FirstOne {
int x = 3;
}
package com.company;
public class SecondOne {
public static void main(String[] args) {
FirstOne obj = new FirstOne();
System.out.println(obj.x);
}
}