Latest web development tutorials

Java objects and classes

Java as an object-oriented language. It supports the following basic concepts:

  • Polymorphism
  • inherit
  • Package
  • abstract
  • class
  • Objects
  • Examples
  • method
  • Overloaded

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

  • Object: The object is an instance of a class (object is not to find a girlfriend), there are state and behavior. For example, a dog is an object whose states are: color, name, breed; behavior: wagging its tail, called, eat and so on.
  • Class: The class is a template that describes the behavior of a class of objects and status.

Boys and girls below the figure for the class, and specific to each class of artificial objects:


Java objects

Now let us understand what is an object. Look around the real world, you will find around a lot of objects, cars, dogs, people, and so on. All of these objects have their own state and behavior.

To take the dog for example, it states are: name, breed, color, behavior: called, wags its tail and ran.

Compare real objects and software objects are very similar between them.

Software objects have state and behavior. State software object is to attribute behavior by the method of expression.

In software development, call each other to change the method of operating the internal state of an object, the object is accomplished by the method.

Java Classes

Class can be seen as a template to create Java objects.

By following a simple class definition to understand Java in class:

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: variable in a method, constructor or statement block definitions is called local variables. Variables are declared and initialized in the method, after the end of the method, the variables will be automatically destroyed.
  • Member variables: class member variables are defined, the variable outside the method body. This variable is created when the object is instantiated. Member variables can be accessed in the statement block class methods, constructors and methods of a particular class.
  • Class variables: class variables declared in a class, a method other than the body, but must be declared as static type.

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


Construction method

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

Creating an object, at least, to be called a constructor. The name of the constructor must be the same name as the class, a class can have multiple constructors.

Here is an example of the constructor:

public class Puppy{
   public Puppy(){
   }

   public Puppy(String name){
      // 这个构造器仅有一个参数:name
   }
}

Create Object

Objects are created based on the class. In Java, use the keyword new to create a new object. Create an object requires the following three steps:

  • Disclaimer: declare an object, including the object name and object type.
  • Examples: the new keyword to create an object.
  • Initialization: Create a new object using the default constructor to initialize the object will be called.

Here is an example of creating an object:

public class Puppy{
   public Puppy(String name){
      //这个构造器仅有一个参数:name
      System.out.println("Passed Name is :" + name ); 
   }
   public static void main(String []args){
      // 下面的语句将创建一个Puppy对象
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

Compile and run the above program will print out the following results:

Passed Name is :tommy

Access instance variables and methods

To access the member variables and member methods through an object has been created, as follows:

/* 实例化对象 */
ObjectReference = new Constructor();
/* 访问其中的变量 */
ObjectReference.variableName;
/* 访问类中的方法 */
ObjectReference.MethodName();

Examples

The following example shows how to access the instance variables and call member methods:

public class Puppy{
   int puppyAge;
   public Puppy(String name){
      // 这个构造器仅有一个参数:name
      System.out.println("Passed Name is :" + name ); 
   }

   public void setAge( int age ){
       puppyAge = age;
   }

   public int getAge( ){
       System.out.println("Puppy's age is :" + puppyAge ); 
       return puppyAge;
   }

   public static void main(String []args){
      /* 创建对象 */
      Puppy myPuppy = new Puppy( "tommy" );
      /* 通过方法来设定age */
      myPuppy.setAge( 2 );
      /* 调用另一个方法获取age */
      myPuppy.getAge( );
      /*你也可以像下面这样访问成员变量 */
      System.out.println("Variable Value :" + myPuppy.puppyAge ); 
   }
}

Compile and run the above program produces the following results:

Passed Name is :tommy
Puppy's age is :2
Variable Value :2

Source file declaration rules

In the last part of this section, we will learn the rules declare the source file. When you define multiple classes in one source file, and there are import statements and package statement, pay special attention to these rules.

  • A source file can have only one public class
  • A source file can have multiple non-public classes
  • The source file name and class name public class should be consistent. For example: class name in the source file public class is Employee, then the source file should be named Employee.java.
  • If a class is defined in a package, the package statement must be the first line of the source file.
  • If the source file containing the import statement, the statement should be placed between the package and class definitions. If there is no package statement, import statements should be foremost in the source file.
  • import package statements and statements of all the classes defined in the source file are valid. In the same source file, not to the different classes of different packages statement.

There are several levels of access class, and the class can be divided into different types: abstract classes and final classes and the like. These are described in the Access Control section.

In addition to the above-mentioned types, Java there are some special categories, such as: inner classes, anonymous classes.


Java package

Package is mainly used to categorize classes and interfaces. When you develop a Java program could write hundreds of classes, so it is necessary to classify classes and interfaces.

Import Statement

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

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

import java.io.*;

A simple example

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

First, open a text editor to paste the following code into it. Note Save the file as Employee.java.

Employee class has four member variables: name, age, designation and salary. Class explicitly declare a constructor method, which is only one parameter.

import java.io.*;
public class Employee{
   String name;
   int age;
   String designation;
   double salary;
   // Employee 类的构造器
   public Employee(String name){
      this.name = name;
   }
   // 设置age的值
   public void empAge(int empAge){
      age =  empAge;
   }
   /* 设置designation的值*/
   public void empDesignation(String empDesig){
      designation = empDesig;
   }
   /* 设置salary的值*/
   public void empSalary(double empSalary){
      salary = empSalary;
   }
   /* 打印信息 */
   public void printEmployee(){
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}

Program execution starts from the main method. To run the program, and must contain a main method creates an instance of an object.

Here are EmployeeTest class, instantiate two instances of the Employee class, and call the method to set the value of the variable.

The following code is stored in EmployeeTest.java file.

import java.io.*;
public class EmployeeTest{

   public static void main(String args[]){
      /* 使用构造器创建两个对象 */
      Employee empOne = new Employee("James Smith");
      Employee empTwo = new Employee("Mary Anne");

      // 调用这两个对象的成员方法
      empOne.empAge(26);
      empOne.empDesignation("Senior Software Engineer");
      empOne.empSalary(1000);
      empOne.printEmployee();

      empTwo.empAge(21);
      empTwo.empDesignation("Software Engineer");
      empTwo.empSalary(500);
      empTwo.printEmployee();
   }
}

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

C :> javac Employee.java
C :> vi EmployeeTest.java
C :> javac  EmployeeTest.java
C :> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0