Java experiment Four and experiment five

Source: Internet
Author: User

Inheritance and polymorphism of four types of experiments

"Developing languages and implementing platforms or experimental environments"

Windows2000 or xp,jdk1.6 and Jcreator4.0

"Experimental Purpose"

1. Mastering the way OOP is programmed,

2. Understand the role of class inheritance and polymorphism.

"Experimental Requirements"

1. Write a program that embodies the inheritance of the class (member variables, member methods, member variables hidden).

2. Write a program that embodies class polymorphism (member method overloading, constructor method overloading).

"Experimental Content"

A class of inheritance exercises

1. Further understanding of the meaning of inheritance

The new class can be generated from existing classes and retains member variables and methods of existing classes and can be modified as needed. New classes can also add new variables and methods. This behavior is called inheritance of classes. When you create a new class, you do not have to write out all the member variables and member methods. Simply declaring that the class inherits from a defined class can refer to all members of the inherited class. The inherited class is called the parent class or superclass (superclass), and the new class is called a subclass. You typically extend a subclass by adding new properties and methods. This makes subclasses larger than the parent class, but more specific, representing a more concrete set of objects. The meaning of inheritance lies in this.

2. Create public class Lx3_7_p

(1) Write the program file Lx3_7_p.java, the source code is as follows.

public class Lx3_7_p

{

protected String XM; Member variable with protection modifier

protected int xh;

void SetData (String m,int h)//method for setting data

{

XM =m;

XH = h;

}

public void print ()//method of output data

{

System.out.println (xm+ "," +xh);

}

}

(2) Compile Lx3_7_p.java, generate class file Lx3_7_p.class.

(3) Creating an inherited class

A program function: The subclass Lx3_8 is generated by the Lx3_7_p class, which not only has the member variables of the parent class XM (name), XH (school number), but also defines the new member variable XY (college), XI (department). The Print method of the parent class is called in the program, and you can see that the child class also has the method.

B Write the Lx3_8.java program, the source code is as follows.

Class Lx3_8 extends lx3_7_p{

protected String xy;

Protected String XI;

public static void Main (String args[])

{

lx3_7_p P1 = new lx3_7_p ();

P1.setdata ("Shuai 0", 12321);

P1.print ();

Lx3_8 S1 = new Lx3_8 ();

S1.setdata ("Guo Lina", 12345); Calling a member method of a parent class

S1.xy= "School of Economic management"; Accessing member variables of this class

s1.xi= "Information Management department"; Accessing member variables of this class

S1.print ();

System.out.print (s1.xm+ "," +s1.xy+ "," +s1.xi ");

}

}

(3) Compile and run the program, as shown in result 6.1.

Figure 6.1

3. Understanding how member variables are hidden

The so-called Hide refers to the subclass redefining the same name variable in the parent class, redefining X to X1,y as Y1 in the subclass line, hiding the two member variables x and y in the parent point. When a subclass executes its own method, it operates on a variable of the subclass, and when the subclass executes the method of the parent class, the action is the variable of the parent class. In subclasses, it is important to pay special attention to the naming of member variables, which prevents the key member variables of the parent class from inadvertently being hidden, which can cause problems for the program.

4. Understanding how member methods are covered

(1) Definition and function of method coverage

Inheriting subclasses can inherit all member methods in the parent class that can be accessed by subclasses, but cannot inherit if the child class's method has the same name as the parent method, which is called a method of the subclass that overrides the method of the parent class, referred to as the method override (override). Method overrides provide the ability for subclasses to modify the parent class member methods. For example, subclasses can modify the ToString method of the object root class inherited by the layer, allowing it to output some more useful information. The following program shows the addition of the ToString method in the subclass circle to return the circle radius and circle area information.

(2) write the program file Lx3_9.java, which covers the ToString method of the object class, with the following source code.

Class Circle {

private int radius;

Circle (int r) {

Setradius (R);

}

public void Setradius (int r) {

Radius=r;

}

public int Getradius () {

return radius;

}

Public double area () {

return 3.14159*radius*radius;

}

Public String toString () {

Return "Circle Radius:" +getradius () + "Circle area:" +area ();

}

}

public class lx3_9{

public static void Main (String args[]) {

Circle C=new Circle (10);

System.out.println ("\ n" +c.tostring ());

}

}

(3) Compile and run the program, as shown in result 6.2

Figure 6.2

(4) Program structure analysis.

The program adds the ToString method and modifies its return value. Because ToString and the inherited object class have the same method name and return value type, the ToString method in the superclass object is overridden.

The method overrides should pay special attention to:

The subclass method used to overwrite should have the same name, the same return value type, and the same number of arguments and parameter types as the overridden parent class method.

5. Use of this, Super and super ()

(1) Program function: Explain the use of this, Super and super (). The program first defines the point (dot) class and then creates the sub-class line of the point. Finally, the length of the segment is output through the Lx3_10 class.

The constructor of the parent class point is called by Super (A, A, a, b) to assign values to the parent class's X and Y. In the Setline method of the subclass line, because the parameter name and the member variable name are the same, to assign a value to the member variable, use this reference to tell the compiler to assign a value to the member variable of the current class. When using the parent class member variable in the length and ToString methods, use the super reference to tell the compiler to use a member variable of the parent class.

(2) The program file Lx3_10.java with this, Super and super (), the source code is as follows.

Class Point {

protected int x, y;

Point (int a, int b) {

SetPoint (A, b);

}

public void SetPoint (int a, int b) {

X=a;

Y=b;

}

}

Class Line extends Point {

protected int x, y;

Line (int a, int b) {

Super (A, b);

Setline (A, b);

}

public void Setline (int x, int y) {

This.x=x+x;

This.y=y+y;

}

public double Length () {

int x1=super.x, Y1=SUPER.Y, x2=this.x, Y2=this.y;

Return Math.sqrt ((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1));

}

Public String toString () {

Return "line end: [" + Super.x + "," + Super.y + "] [" +

x + "," + y + "] line length:" + this.length ();

}

}

public class lx3_10{

public static void Main (String args[]) {

Line Line=new Line (50, 50);

System.out.println ("\ n" +line.tostring ());

}

}

(3) Compile and run the program, as shown in result 3.10.

Figure 3.10

Two types of polymorphism exercises

1. Understanding the polymorphism of a class

The inheritance of a class occurs between multiple classes, and the polymorphism of a class occurs only on the same class. In a class, you can define multiple methods with the same name, as long as you determine that they have different number and type of arguments. This phenomenon is called polymorphism of the class. Polymorphism makes the program simple, which brings great convenience to programmers. In OOP, when a program implements several similar functions, it gives a common name to the corresponding method and represents different functions with different parameters. Thus, when using the method, regardless of the parameters passed, as long as can be recognized by the program can be determined by the results. The polymorphism of a class is embodied in the overloads of the method (overload), including the member methods and the overloads of the construction methods.

2. Overloading of methods

3. Overloading of construction methods

The constructor method has the same name as the class and no return type. The constructor method cannot be called directly, and can only be called by the new operator, which is used primarily to initialize the object. The purpose of the overloaded construction method is to provide the ability to initialize objects in a variety of ways, so that programmers can choose the appropriate construction method to initialize the objects according to their actual needs.

(1) Program function: Write the construction method rundemo the overloaded program file Lx3_12, the source code is as follows.

(2) Source code:

Class Rundemo {

Private String userName, password;

Rundemo () {

System.out.println ("All Empty!");

}

Rundemo (String name) {

Username=name;

}

Rundemo (string name, string pwd) {

This (name);

Password=pwd;

Check ();

}

void Check () {

String S=null;

if (username!=null)

s= "User name:" +username;

Else

s= "User name cannot be empty! ";

if (password!= "12345678")

s=s+ "Password is invalid! ";

Else

s=s+ "Password: ********";

System.out.println (s);

}

}

public class Lx3_12 {

public static void Main (string[] args) {

New Rundemo ();

New Rundemo ("Liu Xinyu");

New Rundemo (NULL, "Shaoliping");

New Rundemo ("Zhang Chi", "12345678");

}

}

(2) Compile and run the program, as shown in result 6.4.

Figure 6.4

"Complete the Experimental project"

1. If we need to model an employee while developing a system, the employee has 3 attributes: Name, work number, and salary. The manager is also an employee, in addition to the attributes of the employee, there is also a bonus attribute. Use the idea of inheritance to design employee and manager classes. Requires that the class provide the necessary methods for property access.

2. Define a mymath of your own math class. class provides a static method, Max, which receives 3 parameters of the same type (such as shaping), returning the maximum value.

3. Take a point class as a base class, derive a circle from a point, derive a cylinder from a circle, and design member functions to output their area and volume.

Experimental five-pack, interface abstract class

"Developing languages and implementing platforms or experimental environments"

Windows2000 or xp,jdk1.6 and Jcreator4.0

"Experimental Purpose"

1. Understand the role of the package, interface (interface), and abstract classes in Java.

2. Master the design method of package, interface and abstract class.

"Experimental Requirements"

1. Understand the structure of the Java System Package.

2. Master the method of creating a custom package.

3. Master the technique of using the system interface and the method of creating the custom interface.

"Experimental Steps"

A Understanding and using the Java System Package

1. The role of API packages, interfaces, exception handling

A package is a collection of classes and interfaces. Packages can be used to put common classes or functions similar classes in a package. The Java language provides a system package that contains a large number of classes that can be referenced directly when writing Java programs. All Java API packages are in "java." Start with a different user-created package. The interface solves the problem that Java does not support multiple inheritance, and can achieve the same functionality as multiple inheritance by implementing multiple interfaces. The error of the handler runtime is as important as the design program, and the software system can run stably for a long time only if it can perfect the program that handles the run-time error, and exception handling is the problem of how to handle the error when the program runs.

Two Create and use a custom package

1. Customizing how packages are declared

<package> < custom package names >

The declaration package statement must be added to the first line of the source program, indicating that all classes declared by the program file belong to this package.

2. Create a custom package MyPackage

Create a subfolder mypackage in the folder where the source program is stored. For example, in the E:\javademo folder, create a subfolder mypackage (E:\javademo\Mypackage) with the same name as the package, and put the compiled class file in the folder. Note: The package name is identical to the folder name case. Add the path to the environment variable classpath, for example: D:\java\jdk1.6\lib; E:\javademo

3. To create a class in a package

(1) Ymd.java program function: In the source program, first declare the use of the package name MyPackage, and then create the YMD class, which has the year of calculation, you can output a string with a month and date function.

(2) write the Ymd.java file, the source code is as follows.

Package mypackage; Declaring a package that holds classes

Import java.util.*; Reference Java.util Package

public class Lx4_1_ymd {

private int year,month,day;

public static void Main (string[] arg3) {}

Public lx4_1_ymd (int y,int m,int d) {

Year = y;

Month = (((m>=1) & (m<=12)) m:1);

Day = (((d>=1) & (d<=31)) d:1);

}

Public Lx4_1_ymd () {

This (0,0,0);

}

public static int Thisyear () {

Return Calendar.getinstance (). get (Calendar.year);//Returns the year of the Year

}

public int year () {

Return year;//returns the year

}

Public String toString () {

return year+ "-" +month+ "-" +day;//returns the year-month-day converted to a string

}

}

(3) Compile the Lx4_1_ymd.java file, and then store the Lx4_1_ymd.class file in the MyPackage folder.

3. Writing programs that use the Lx4_1_ymd class in package MyPackage

(1) Lx4_2.java program function: Given a person's name and date of birth, calculate the person's age, and output the person's name, age, date of birth. The program uses the Lx4_1_ymd method to calculate the age.

(2) write the Lx4_2.java program file, the source code is as follows.

Import Mypackage.lx4_1_ymd; Referencing the Lx4_1_ymd class in the MyPackage package

public class Lx4_2

{

private String name;

Private LX4_1_YMD birth;

public static void Main (String args[])

{

Lx4_2 a = new Lx4_2 ("Zhang Chi", 1990,1,11);

A.output ();

}

Public Lx4_2 (String n1,lx4_1_ymd d1)

{

name = N1;

birth = D1;

}

Public Lx4_2 (String n1,int y,int m,int D)

{

This (n1,new Lx4_1_ymd (y,m,d));//Initialize Variables and objects

}

public int Ages ()//Calculate Age

{

Return Lx4_1_ymd.thisyear ()-birth.year (); Returns the difference between the year before and the age of birth

}

public void output ()

{

System.out.println ("Name:" +name);

System.out.println ("Date of Birth:" +birth.tostring ());

System.out.println ("Age of the Year:" +age ());

}

}

(3) Compile and run the program, as shown in result 8.1.

Figure 8.1

Three Using interface Technology

1. Definition and function of interface

An interface can be thought of as a collection of methods and constants that are not implemented. Interfaces are similar to abstract classes in that the methods in an interface simply declare and do not define any specific methods of operation. Interfaces are used to solve problems in the Java language that do not support multiple inheritance.

(1) Define an interface shape2d, use it to achieve two-dimensional geometric shape class circle and Rectangle area calculation program file to implement the interface

(2) Source code:.

Interface shape2d{//define SHAPE2D interface

Final double pi=3.14; Data members must be initialized

public abstract double area (); Abstract method, do not need to define the processing mode

}

Class Circle implements shape2d{

Double radius;

Public Circle (Double R) {//constructor method

Radius=r;

}

Public double area () {

Return (PI * radius * radius);

}

}

Class Rectangle implements shape2d{

int width,height;

Public Rectangle (int w,int h) {//constructor method

Width=w;

Height=h;

}

Public double area () {

Return (width * height);

}

}

public class Interfacetester {

public static void Main (String args[]) {

Rectangle rect=new Rectangle (5,6);

System.out.println ("area of rect =" + Rect.area ());

Circle Cir=new Circle (2.0);

System.out.println ("area of Cir =" + Cir.area ());

}

}

"Complete the Experimental project"

1. Define an abstract base class shape, which contains three abstract methods center (), diameter (), Getarea (), derive the square and circle classes from the shape class, and all two classes use center () to compute the object's central coordinates. Diameter () calculates the outer circle diameter of the object, and the Getarea () method calculates the area of the object. Write the application using the rectangle class and the Circle class.

2. Defines an interface insurance, with four abstract methods in the interface: public int getpolicynumber (); public int getcoverageamount (); public double Calculatepremium (); public Date getexpirydate (). Design a class car, the class implements the method of the interface, writing the application.

Java experiment Four and experiment five

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.