Home > Java > javaTutorial > body text

Deep understanding of Java objects and classes

高洛峰
Release: 2017-01-20 17:31:17
Original
1687 people have browsed it

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

•Polymorphism
•Inheritance
•Encapsulation
•Abstract
•Class
•Object
•Instance
•Method
•Message Analysis

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

•Object: An object is an instance of a class and has state and behavior. For example, a dog is an object. Its status includes: color, name, and breed; its behaviors include: wagging its tail, barking, eating, etc.

•Class: A class is a template that describes the behavior and status of a type of object.

Objects in Java

Now let’s take a deeper look at what an object is. If you look at the real world around you, you will find that there are many objects around you, such as cars, dogs, people, etc. All these objects have their own state and behavior.

Take a dog as an example. Its status includes: name, breed, and color. Its behaviors include: barking, wagging its tail, and running.

Comparing real objects and software objects, they are very similar.

Software objects also have state and behavior. The state of a software object is its attribute, and its behavior is reflected through methods.

In software development, methods operate on changes in the internal state of objects, and mutual calls between objects are also completed through methods.

Classes in Java

Classes can be seen as templates for creating Java objects.

Let’s understand the definition of a class in Java through the following simple class:

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

A class can contain the following types of variables:

•Local variables: Variables defined in methods, constructors or statement blocks are called local variables. Variable declaration and initialization are all in methods. After the method ends, the variables will be automatically destroyed.

•Member variables: Member variables are variables defined in the class and outside the method body. This type of variable is instantiated when the object is created. Member variables can be accessed by class methods, constructors, and class-specific statement blocks.

•Class variables: Class variables are also declared in the class, outside the method body, but must be declared as static type.

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

Constructor method

Every class has a constructor method. If no constructor is explicitly defined 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 be the same as the class. A class can have multiple constructors.

The following is an example of a constructor method:

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

Creating objects

Objects are created based on 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 using new to create an object, the constructor method will be called to initialize the object.

The following 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" );
  }
}
Copy after login

Compile and run the above program, the following results will be printed:

Passed Name is :tommy

Access instance variables and methods

Access member variables and member methods through the created object, as follows:

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

The following example shows how to access 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 );
  }
}
Copy after login

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 declaration rules for source files. Pay special attention to these rules when defining multiple classes in a source file and when there are import statements and package statements.

•There can only be one public class in a source file

•A source file can have multiple non-public classes

•The name of the source file should be the same as that of the public class Class names remain consistent. For example: the class name of the public class in the source file is Employee, then the source file should be named Employee.java.

•If a class is defined in a package, the package statement should be on 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, different package declarations cannot be given to different classes.

Classes have several access levels, and classes are also divided into different types: abstract classes, final classes, etc. These will be introduced in the access control chapter.

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

Java Package

Package is mainly used to classify classes and interfaces. When developing Java programs, you may write hundreds or thousands of classes, so it is necessary to classify classes and interfaces.

Import statement

In Java, if a complete qualified name is given, including the package name and class name, 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 certain class.

例如,下面的命令行将会命令编译器载入java_installation/java/io路径下的所有类

import java.io.*;

一个简单的例子

在该例子中,我们创建两个类:Employee和EmployeeTest。

首先打开文本编辑器,把下面的代码粘贴进去。注意将文件保存为Employee.java。

Employee类有四个成员变量:name、age、designation和salary。该类显式声明了一个构造方法,该方法只有一个参数。

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);
  }
}
Copy after login

程序都是从main方法开始执行。为了能运行这个程序,必须包含main方法并且创建一个实例对象。

下面给出EmployeeTest类,该类实例化2个Employee类的实例,并调用方法设置变量的值。

将下面的代码保存在EmployeeTest.java文件中。

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();
  }
}
Copy after login

编译这两个文件并且运行EmployeeTest类,可以看到如下结果:

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
Copy after login

以上这篇深入理解Java 对象和类 就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持PHP中文网。

更多深入理解Java 对象和类相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!