Java objects and Classes

Source: Internet
Author: User

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

  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Class
  • Object
  • Instance
  • Method
  • Message Parsing
This section focuses on the concepts of objects and classes.
  • Object: an object is an instance of a class and has statuses and behaviors. For example, a dog is an object in the following states: color, name, breed, and behavior: tail shaking, calling, and eating.
  • Class: A class is a template that describes the behavior and status of a class of objects.

 

Objects in Java

Now let's have a deep understanding of what objects are. Looking at the real world around you, you will find many people around you, such as cars, dogs, and people. All these objects have their own States and actions.

Take a dog for example. Its status includes name, breed, color, and behavior: name, tail, and run.

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

Software objects also have statuses and behaviors. The state of a software object is an attribute, and its behavior is reflected by a method.

In software development, when the internal state of a method operation object changes, the mutual call of objects is also completed through methods.

 

Classes in JavaClass can be seen as a template for creating Java objects. The following is a simple class to understand the definition of classes 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 variable: Variables defined in methods, constructor methods, or statement blocks are called local variables. Both the variable declaration and initialization are in the method. After the method is completed, the variable 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 an object is created. Member variables can be accessed by methods, constructor methods, and statement blocks of specific classes.
  • Class variable: Class variables are also declared in the class, except the method body, but must be declared as static type.

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

 

Constructor

Each class has a constructor. If no constructor is explicitly defined for the class, the Java compiler provides a default constructor for the class.

You must call at least one constructor when creating an object. The name of the constructor must be the same as that of the class. A class can have multiple constructor methods.

The following is a constructor example:
Public class Puppy {public Puppy () {} public Puppy (String name) {// This constructor has only one parameter: name }}

 

Create object

The object is created based on the class. In Java, use the keyword "new" to create a new object. To create an object, follow these steps:

  • Declaration: declares an object, including the Object Name and object type.
  • Instantiation: Create an object with the keyword "new.
  • Initialization: when an object is created using new, the constructor is called to initialize the object.
The following is an example of creating an object:
Public class Puppy {public Puppy (String name) {// This constructor has only one parameter: name System. out. println ("Passed Name is:" + name);} public static void main (String [] args) {// The following statement creates a Puppy object Puppy myPuppy = new Puppy ("tommy ");}}

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

Passed Name is :tommy

 

Access instance variables and MethodsAccess member variables and member methods through created objects, as shown below:
/* Instantiate object */ObjectReference = new Constructor ();/* access the variable */ObjectReference. variableName;/* methods in the handler class */ObjectReference. MethodName ();
The following example shows how to access instance variables and call Member methods:
Public class Puppy {int puppyAge; public Puppy (String name) {// This constructor has only one parameter: 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) {/* Create object */Puppy myPuppy = new Puppy ("tommy");/* set age */myPuppy by using the method. setAge (2);/* call another method to get age */myPuppy. getAge ();/* You can also access the member variable */System as follows. out. println ("Variable Value:" + myPuppy. puppyAge );}}

Compile and run the above program to generate the following results:

Passed Name is :tommyPuppy's age is :2Variable Value :2

 

Source File Declaration Rules

At the end of this section, we will learn the Declaration Rules of source files. Pay special attention to these rules when defining multiple classes in a source file, including import statements and package statements.

  • One source file can only have one public class.
  • A source file can have multiple non-public classes.
  • The source file name must be consistent with the Class Name of the public class. For example, if the class name of the public class in the source file is "Employee", the source file should be named "Employee. java.
  • If a class is defined in a package, the package statement should be in the first line of the source file.
  • If the source file contains the 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 the first in the source file.
  • The import Statement and package statement are valid for all classes defined in the source file. Different classes cannot be declared for different packages in the same source file.

The class has several access levels, and the class is also divided into different types: abstract class and final class. These are described in the Access Control Section.

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

 

Java package

Packages are mainly used to classify classes and interfaces. When developing a Java program, hundreds of classes may be written. Therefore, it is necessary to classify classes and interfaces.

 

Import Statement

In Java, if a complete qualified name, 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 class.

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

import java.io.*;

 

A simple example

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

Open the text editor and paste the following code. Save the file as Employee. java.

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

Import java. io. *; public class Employee {String name; int age; String designation; double salary; // The constructor of the Employee class public Employee (String name) {this. name = name;} // set the value of age to public void empAge (int empAge) {age = empAge;}/* set the value of designation */public void empDesignation (String empDesig) {designation = empDesig;}/* set salary value */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 ("Designation:" + designation); System. out. println ("Salary:" + salary );}}

  

All programs are executed from the main method. To run this program, you must include the main method and create an instance object.

The following describes the EmployeeTest class, which instantiates two instances of the Employee class and calls a method to set the variable value.

Save the following code in the EmployeeTest. java file.
Import java. io. *; public class EmployeeTest {public static void main (String args []) {/* use the constructor to create two objects */Employee empOne = new Employee ("James Smith "); employee empTwo = new Employee ("Mary Anne"); // call the member method empOne of the two objects. 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 these two files and run the EmployeeTest class. The following result is displayed:

C :> javac Employee.javaC :> vi EmployeeTest.javaC :> javac  EmployeeTest.javaC :> java EmployeeTestName:James SmithAge:26Designation:Senior Software EngineerSalary:1000.0Name:Mary AnneAge:21Designation:Software EngineerSalary:500.0

  

Address: http://www.manongjc.com/java/java_object_classes.html

Java-related reading materials:

  • Java tutorial
  • Java Quick Start
  • Java Development Environment Configuration
  • Java basic syntax
  • Java objects and Classes
  • Java Basic Data Type
  • Java variable type
  • Java Modifier
  • Java Operators
  • Java Loop Structure
  • Java Branch Structure
  • Java Number
  • Java Character class
  • Java String class
  • Java StringBuffer and StringBuilder classes
  • Java Array
  • Java date and time
  • Java Regular Expression
  • Java method
  • Java Stream, File, and IO
  • Java Exception Handling

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.