Java Objects and Classes

Java is an object-oriented language. The following basic concepts are supported:

  • Polymorphism
  • inherit
  • Packaging
  • abstract
  • class
  • Objects
  • Examples
  • method
  • Heavy load

In this section we focus on the concepts of objects and classes.

  • Object : An object is an instance of a class (the object is not a girlfriend ) and has state and behavior. For example, a dog is an object, its state is: color, name, breed; behavior: waving tail, calling, eating and so on.
  • Class : A class is a template that describes the behavior and state of a class of objects.

The boys and girls in the figure below are classes, and each individual is the object of this class:


Objects in Java

Let us now understand in depth what is an object. If you look around at the real world around you, you will find lots of objects, cars, dogs, people and so on. All these objects have their own state and behavior.

Take a dog for example. Its status is: name, breed, color, behavior: calling, waving tail, and running.

Compared with real objects and software objects, they are very similar.

Software objects also have state and behavior. The state of the software object is an attribute, and the behavior is reflected by the method.

In software development, the internal state of the method operation object is changed, and the mutual calling of objects is also accomplished by methods.

Classes in Java

Classes can be seen as templates for creating Java objects.

Use the following simple class to understand the definition of a class in Java:

public class Dog { String breed ;int age ;String color ;void barking () {}void hungry () {}void sleeping () {} }

A class can contain the following types of variables:

  • Local variables : Variables defined in a method, constructor, or statement block are called local variables. Variables are declared and initialized in the method. After the method ends, the variable is automatically destroyed.
  • Member variables : Member variables are defined in the class, outside the body of the method. This variable is instantiated when the object is created. Member variables can be accessed by methods, constructors, and statement blocks of specific classes in the class.
  • Class variables : Class variables are also declared in the class, outside the body of the method, but must be declared as static.

A class can have multiple methods. In the above example: barking(), hungry(), and sleeping() are methods of the Dog class.


Construction method

Each class has a constructor. If you do not explicitly define a constructor for a class, the Java compiler will provide a default constructor for the class.

When creating an object, at least one constructor must be called. The name of the constructor must have the same name as the class. A class can have multiple constructors.

Here is an example of a constructor method:

public class Puppy {        public Puppy ( ) {   }        public Puppy ( String name ) {           // This constructor has only one argument: name   } }

Create an object

Objects are created from classes. In Java, use the keyword new to create a new object. Creating an object requires the following three steps:

  • Declaration : declare an object, including the object name and object type.
  • Instantiation : Use the keyword new to create an object.
  • Initialization : When you create an object with new, the constructor initializes the object.

Here is an example of creating an object:

public class Puppy {        public Puppy ( String name ) {               // This constructor has only one parameter: name               System.out.println ( "The puppy's name is: " + name ) ; }        public static void main ( String [ ] args ) {               // The following statement will create a Puppy object               Puppy myPuppy = new Puppy ( "tommy" ) ;  } }
Compiling and running the above program will print the following result:The puppy's name is: tommy : tommy

Access instance variables and methods

The member variables and member methods are accessed through the created object as follows:

/ * Examples of objects * /ObjectReference = new Constructor ( ) ; / * access class variables * /ObjectReference . VariableName ; / * Method access class * /ObjectReference . MethodName ( ) ;

Examples

The following example shows how to access an instance variable and call a member method:

public class Puppy {int puppyAge;public Puppy(String name) {System.out.println("The puppy's name is: " + name);}public void setAge(int age) {puppyAge = age;}public int getAge() {System.out.println("The puppy's age is : " + puppyAge);return puppyAge;}public static void main(String[] args) {Puppy myPuppy = new Puppy(" tommy ");myPuppy.setAge(2);System.out.println(" variable value: " + myPuppy.puppyAge);}}

Compile and run the above program with the following results:

The name of the puppy is: tommy : tommyThe puppy's age is: 2The puppy's age is : 2  Variable value: 2Variable value : 2  

Source file declaration rules

In the final part of this section, we will learn the rules of declaration of source files. When defining multiple classes in a source file, and also import statements and package statements, pay special attention to these rules.

  • There can be only one public class in a source file
  • A source file can have more than one non-public class
  • The name of the source file should be the same as the class name of the public class. For example: The class name of the public class in the source file is Employee, so the source file should be named Employee.java.
  • If a class is defined in a package, then the package statement should be in the first line of the source file.
  • If the source file contains an import statement, it should be placed between the package statement and the class definition. If there is no package statement, the import statement should be first in the source file.
  • The import statement and package statement are valid for all classes defined in the source file. In the same source file, you cannot declare different packages with different classes.

Classes have several levels of access, and classes are also divided into different types: abstract classes and final classes. These will be introduced in the Access Control section.

In addition to the types mentioned above, Java has some special classes, such as: inner classes, anonymous classes.


Java package

Packages are mainly used to classify classes and interfaces. When developing Java programs, hundreds or thousands of classes may be written, so it is necessary to classify classes and interfaces.

Import statement

In Java, if you give a full qualified name, including the package name, class name, then the Java compiler can easily locate the source code or class. The Import statement is used to provide a reasonable path so that the compiler can find a class.

For example, the following command line will command the compiler to load all classes in the java_installation/java/io path

import java.io.*;java.io.*;

A simple example

In this example, we create two classes: Employee and EmployeeTest .

First open the text editor and paste the following code into it. Note that the file is saved as Employee.java.

The Employee class has four member variables: name, age, designation, and salary. This class explicitly declares a constructor that has only one argument.

Employee.java file code:

import java . io .*; public class Employee {  String name ; int age ; String designation ; double salary ;  // Constructor for the Employee class  public Employee ( String name ) {  this . name = name ;  }   // Set the value of age  public void empAge ( int empAge ) {  age = empAge ; }   /* set the value of designation */  public void empDesignation ( String empDesig ) {  designation = empDesig ; }   /* set the value of salary */  public void empSalary ( double empSalary ) {  salary = empSalary ; }   / * print information * /  public void printEmployee ( ) {  System . out . println ( " Name: " + name ) ; System . out . println ( " Age: " + age ) ; System . out . println ( " Post: " + designation ) ; System . Out . println ( "Salary: " + salary ) ; }}
Programs are started from the main method. To be able to run this program, you must include the main method and create an instance object.

The EmployeeTest class is given below, which instantiates two instances of the Employee class and calls the method to set the value of the variable.

Save the following code in the EmployeeTest.java file.

EmployeeTest.java file code:

import java . io .*;public class EmployeeTest {public static void main ( String [ ] args ) {/* use the constructor to create two objects */Employee empOne = new Employee ( " Bubbule1 " ) ;Employee empTwo = new Employee ( " Bubbule2 " ) ;// Call member methods of these two objects empOne . empAge ( 26 ) ;empOne . empDesignation ( " advanced programmer " ) ;empOne . empSalary ( 1000 ) ;empOne . printEmployee ( ) ;empTwo . empAge ( 21 ) ;empTwo . empDesignation ( " rookie programmer " ) ;empTwo . empSalary ( 500) ;empTwo . printEmployee ( ) ;}}

Compile these two files and run EmployeeTest class, you can see the following results:

$ javac EmployeeTest.javaEmployeeTest . java$ java EmployeeTest EmployeeTest Name: Bubbule1 Name: Bubbule1Age: 26Age: 26Position: Senior programmerPosition: Senior programmerSalary: 1000.0Salary: 1000.0Name: Bubbule2 Name: Bubbule2Age: 21 Age: 21Position: rookie programmer Position: rookie programmerSalary:500.0Salary: 500.0