Java Constructor Example (construction method) _java

Source: Internet
Author: User

Testcar.java

Copy Code code as follows:

public class Testcar {
public static void Main (string[] args) {
Car C1 = new car ();
C1.color = "Red";
C1.brand = "xxx";//If the car has many properties, so one by one assignment is not very troublesome? Is there a way to set its properties (initialization) as soon as it is produced? There are ~ ~ ~ Look below
}
}

Class Car {
String color;
String brand;

void Run () {
System.out.printf ("I am running...running.") Running~~~~\n ");
}

void ShowMessage () {
System.out.printf ("Car color:%s, car brand:%s\n", color, brand);
}
}

The improved Testcar_ex.java

Copy Code code as follows:

/* What is the construction method * *
public class Testcar_ex {
public static void Main (string[] args) {
Car C1 = new Car ("Red", "xxx");
}
}

Class Car {
String color;
String brand;

Public car (string color, string brand) {
This.color = color; Here is what this object means. The first color is the color property of this object, and the second is the local variable color
This.brand = brand; Ditto
}

void Run () {
System.out.printf ("I am running...running.") Running~~~~\n ");
}

void ShowMessage () {
System.out.printf ("Car color:%s, car brand:%s\n", color, brand);
}
}

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.