Encapsulation, inheritance and polymorphism of java--class

Source: Internet
Author: User
Tags modifiers shallow copy

I. Classes and objects

1. Class

A class is a package of data and a set of operations on the data.

The format of the class declaration:

class declaration

{

Declaration of the member variable;

Declaration and implementation of member methods;

}

1.1 Declaring classes

[Modifier] class < generics > [extends Parent class] [implements interface list]

< the parameters of the generic >--class, and the class with the parameter becomes a generic class.

1.2 Declaring member variables and member methods

Member variable declaration format: [modifier] Data type variable [= expression]{, variable [= expression]};

Member Method--used to describe the operation on a member variable, format: [modifier] Return value type method ([parameter list]) [throws Exception class]
{
Statement sequence;
[return [value]];
}

For example:

public class MyDate//class declaration

{

int year,month,day; Declaring member variables

void set (int y,int m,int D)//member method, set date value

{//No return value, three parameters

Year=y;

Month=m;

Day=d;

}

}

2. Objects

The class itself is not involved in running the program, and the object that actually participates is the class.

An object is an instance of a class (instance), which is the value of a class. An object of the class can obtain and save an instance of the class.

Analogy: Classes--objects--instances of classes

Data type ——— variable--take value

Example: int type--variable i--value 10

2.1 mydate D=new mydate ();//Declaring an object, creating an instance and assigning a value

2.2 Referencing an object's member variables and calling member methods

Object. Member variables

Object. Member method ([parameter list])

Note: Java's automatic memory management mechanism, can track the use of storage units, automatically reclaim resources that are no longer used, so the program does not need to release the space resources occupied by the object.

Java classes are reference data types, and assignments between two objects are reference assignments, and no new instances are created during the assignment of an object.

(Note: 1, "= =" role in the reference data type, determine whether the memory address is equal, want to judge the content entity with equals;
2, the basic transmission of the value of the transfer is a copy, the original value is unchanged after the change, the reference value of the pass-through is the address, modified the original value changes.

A reference type is a data type stored in a variable that is not a value but an in-memory address.
That is, the variable stores the value of the variable in the memory of the address of each call to this variable is to refer to this address and get the real value so called reference type. popularly said, the variable name and the value of the variable, such as Student s=new Student (), S is a reference type of variable, s name is allocated in the stack space, but s it points to the value in the heap space)

Ii. Encapsulation of Classes

1. Construction method

Used to create an instance of the class and initialize the member variables of the instance. The constructor method has the same name as the class, and the construction method is called by the new operator.

The differences between the construction method and the member method are:

A. Different roles: The member method implements the operation of the member variables in the class; The constructor method is used to create an instance of the class and initialize the member variables of the instance.

B. The invocation is different: The Member method is called through the object, and the construction method is called through the new operator.

For example:

public class MyDate

{

Public mydate (int y,int m,int D)

{

Year=y;month=m;day=d;

}

}

The custom constructor method is called with the new operator, and the arguments must conform to the declaration of the constructed method.

MyDate d=new mydate (2009,7,18);//Create an instance and initialize the member variable

Copy construction method

The constructor of a class, if its argument is the class object, called the copy construction method, it initializes the new object that is created to the instance value of the formal parameter, implementing the object replication functionality.

Java does not provide a default copy construction method.

public class Myjava {

public static void Main (string[] args) {
TODO auto-generated method stubs
Myjava d1=new Myjava (2016,4,27);
Myjava d2=new Myjava (D1);
System.out.print (d2.year);
}

private int year;
private int month;
private int day;

Public Myjava (int y,int m,int d) {
Year = y;
Month=m;
Day=d;
}
Public Myjava (Myjava D) {
Year = D.year;
Month=d.month;
Day=d.day;
}

Output: 2016

2.this Reference and Instanceof object operators

2.1 This reference

(1) refers to the object itself this

This is used to refer to the current object itself that invokes the member method.

(2) Accessing member variables and member methods of this class

this. Member variable

This. Member method ([parameter list])

Public mydate (Int. year,int Month,int Day)

{//Specify constructor for parameter, parameter has the same name as member variable

THIS.YEAR=YEAR;//THIS.YEAR Specifies the member variable of the current object, year refers to the parameter

This.month=month;//this references cannot be omitted

This.day=day;

}

Public mydate ()//default construction method, overloading

{

This (1970,1,1);//Call this class already defined construction method

}

Public mydate (MyDate D)

{

This (d.year,d.month,d.day);

}

2.2 Instanceof Object Operators

Returns a Boolean type that determines whether an object belongs to the specified class and its subclasses.

Example: MyDate d=new mydate ();

D instanceof MyDate

Return True,d is an instance of the MyDate class

3 Access Control

Access control permissions for Class 3.1

There are only two types of permission modifiers that can be used by declaring a class: public and Default

Common permissions public, accessible by all classes

The default permission has no modifiers and can be accessed by the class in the current package (the current folder).

You can declare more than one class in a source program file, but a class that is decorated with public can have only one, and that thunder must be the same as the file name.

Several classes can be declared in the source program file Mydate.java as follows:

public class MyDate//publicly-privileged classes

Class MYDATE_EX//default permission classes

Members of the class have 4 access control permissions

Private-declares a private member that can be accessed only by members of the current class. (Current Class)

Default-no modifier represents the default permission, stating that the member can be accessed by the current class and other classes in the current package, also known as visible in the current package. (Current package)

Protected-declares a protected member that can be accessed by the current class and its subclasses, or by other classes in the current package, also known as visible in subclasses. (subclass)

public--declares a public member that can be accessed by all classes. All

Declares the set () and get () methods to access an attribute of an object-a property or characteristic of a value object

Java Conventions, the methods for accessing object properties are set () and get () respectively.

public void Set (Int. y,int M,int Day)//Set Date

public void Set (MyDate D)//set date, reload

public int getYear ()//Get Year

4 Static Members

Instance members-belong to an object, including instance member variables and member methods. Instance member variables and instance member methods can be accessed through objects only if an instance is created.

Static members-belong to the class and need to be identified with the keyword static. Includes class member variables and class member methods. Even if you do not create an instance, you can access the class static member variable and call the static member method directly through the class name.

5 destructor method

--Used to release instances and perform specific actions.

public void Finalize ()//Convention destructor method named Finalize

{//finalize () has no parameters and no return value

Statement sequence;

}//A class can have only one finalize () method, Qiefinalize () forbid overload

Java's automatic memory management mechanism frees up objects that will no longer be used, so the usual class does not need to design a destructor method.

A class can declare a destructor if it needs to perform a specific action when the object is disposed.

Note: A. When an object is outside its scope, Java executes the object's destructor method.

B. An object can also call a destructor to free itself of objects.

C. You cannot use an object that has been disposed of by the destructor, or a run error will occur.

For example: D.finalize (); The destructor method of the calling object

6 Shallow copy with deep copy

Shallow copy-a copy construction method of a class that uses a known instance to assign a value to a member variable of a newly created instance, which is called a shallow copy.

When the member variable of an object is the base data type, the member variables of two objects already have storage space, and the assignment operation passes the value, so a shallow copy can assign a value to an instance.

When a member variable of an object is a reference data type, a shallow copy does not implement the object copy function and requires a deep copy.

public class Person

{

String name; Name

MyDate birthday; Birthday

Public person (String name,mydate birthday)//constructor method

{

This.name=name;

This.birthday=birthday; Reference assignment

}

Public person (person p)//Copy construction method, copy Object

{

This (p.name,p.birthday);

}

}

Deep copy-When a class contains a member variable of a reference type, the copy construction method of the class is not only to copy all non-reference member variable values of the object, but also to create a new instance of the member variable of the reference type and initialize it to the formal parameter instance value, which is called a deep copy.

Three types of inheritance

1 derived classes by inheritance

Inheritance: Creates a class from a known class by inheriting it so that the newly created class automatically owns all the members of the inherited class.

Parent class/Superclass--inherited class; subclass/Derived class--new class generated by inheritance

Relationship of parent class and child class:

A. Subclasses automatically have all members of the parent class, including member variables and methods, so that the parent class members can inherit and continue;

B. Subclasses can change the members inherited from the parent class, adapting the parent class members to the new requirements;

C. Subclasses can also add their own members, allowing the functionality of the class to be expanded.

D. Subclasses cannot delete members of the parent class.

Declaration Inheritance class: [Modifier] class < generic >[extends parent] [implements interface list]

Note: Java classes are single-inheritance, a class can have only one parent class, and cannot have more than one parent class.

1.1 Principles of succession

(1) Subclass inherits member variables of parent class

(2) Subclass inherits a member method other than the constructor method for the parent class

(3) Subclasses cannot inherit the parent class's constructor method

The subclass does not inherit the constructor of the parent class, because the constructor method of the parent class can only create the parent class instance and initialize it, and the instance cannot be created.

For example: The parent class declares the constructor method person (string,mydate), and when the subclass does not have a life student (String,mydate) constructor method, the following statements are incorrect:

Student s1=new Student ("Ted", New MyDate (1979,3,15));//Syntax error, construction method parameter mismatch

(4) Subclasses can add members and can redefine members inherited from the parent class, but cannot be deleted.

1.2 How to construct subclasses

A subclass object contains member variables that inherit from its parent class, as well as member variables declared by the subclass, which must be initialized by the subclass constructor method. The parent class construction method has initialized the member variables declared by the parent class, so the subclass constructor method must call one of the constructor methods of the parent class.

1.2.1 using super () to call the parent class construction method

In the construction method body of a subclass, you can call the constructor of the parent class using super reference. Its syntax is as follows:

Super ([parameter list])

Public Student (String name,mydate birthday,string spec)

{

Super (Name,birthday); The super () call must be the first statement to invoke the constructor of the parent-similar parameter

This.speciality=spec;

}

1.2.2 Default Execution Super ()

In the following two cases, the Java default value type super () calls the constructor of the parent class.

(1) When a class does not declare a constructor method, Java provides the default constructor method for the class, calling Super () to perform a constructor with no arguments to the parent class.

Default construction method provided by public Student ()//java

{

Super (); Calling the parent class constructor method person ()

}

If the parent class person does not declare the constructor method person (), the above statement produces a compilation error. Therefore, each class declares a constructor with no parameters, even if it is not used, and is prepared for the subclass.

Default construction method provided by public person ()//java

{

Super (); Calling the parent class construction method object ()

}

(2) If the subclass's construction method does not call super () or this (), Java will default to super ().

Public Student ()

{

Super ();

Speciality= "";

}

Polymorphism of Class 1.3

The polymorphism of the class is represented by polymorphism of the method and the type of polymorphism.

Method Polymorphism: Includes method overrides and overloads, providing multiple implementations for a function.

Polymorphism of type: A subclass is a type of parent class.

Subclass redefine parent class members include:

(1) To redefine the member variables of the parent class, the member variables of the parent class are hidden;

(2) Redefine the member method of the parent class, overriding the Member method of the parent class if the argument list is the same, otherwise overloaded.

Subclasses redefine the parent class to behave polymorphic, the parent class object refers to the parent class member, and the subclass object refers to the child class member.

In a member method of a subclass, you can use the Super reference if you need to reference a parent-like member that is hidden or overwritten by a quilt class. The format is as follows:

Super. Member variables

Super. Member method ([parameter list])

The subclass object is the parent object-the Subclass object contains all the member variables of the parent class, and ISA relationship behaves as if the inheritance has a nature of "that is." New Person ()/student () instanceof person

Parent class object reference subclass instance--Parent class object can reference subclass instance

Person P=new Student ();

1.3.1 Compile-time polymorphic and run-time polymorphism

(1) Compile-time polymorphism

For multiple methods with the same name, it is called compile-time polymorphism if it is possible at compile time to determine which of the methods in the same name are executed.

Overloading of methods-all compile-time polymorphism

Override of Method-when the object references this class instance, it is a compile-time polymorphic;

Otherwise, run-time polymorphism.

Person P1=new person ("Ted", New MyDate (1979,3,15));

System.out.println ("P1:" +p1.tostring ()); Compile-time polymorphism, executing ToString () of the person class

(2) Run-time polymorphism

The parent class object can only execute a subclass method that is declared in the parent class, overridden by the quilt class, such as ToString (), and cannot execute the newly added member method in the subclass.

When the program runs, Java starts looking for a matching method execution from the class to which the instance belongs, and if there is no matching method in the current class, follow the inheritance layer up and look for the matching method in the parent class and in each ancestor class, until the object class.

Abstract of the four classes

Abstract class Features: 1) Abstract classes may not contain abstract methods, but the classes containing abstract methods must be declared as abstract classes;

2) constructor method, static member method cannot be declared as abstract method;

3) A non-abstract class must implement all the abstract methods inherited from the parent class, and if all the abstract methods of the parent class cannot be implemented, then the class must be declared as an abstract class;

4) Abstract classes cannot be instantiated, and abstract class instances cannot be created.

Encapsulation, inheritance and polymorphism of java--class

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.