Java class and object 8, Java Class Object 8

Source: Internet
Author: User

Java class and object 8, Java Class Object 8

Write Java applications as required.

(1) create a class called People:

Attribute: name, age, gender, height, behavior: speaking, computing addition, rename

Compile a constructor that can assign values to all attributes;

(2) create a primary class:

Create an object named "Zhang San", Gender "male", age 18 years old, height 1.80;

Let this object call the member method: 1) say "Hello !" 2) calculate the value of 23 + 45. 3) change the name to "Li Si"

1 public class People {2 3 private String name; 4 private String sex; 5 private int age; 6 private double height; 7 8 public String getName () {9 return name; 10} 11 12 public void setName (String name) {13 this. name = name; 14} 15 16 People (String name, String sex, int age, double height) {17 this. name = name; 18 this. sex = sex; 19 this. age = age; 20 this. height = height; 21} 22 23 public void sayHi (){ 24 System. out. println (this. name + ": Hello! "); 25} 26 27 public double doAdd (double a, double B) {28 return a + B; 29} 30 31 public void gaiMingZi (String name) {32 this. name = name; 33 34} 35 36 public static void main (String [] args) {37 People p1 = new People ("James", "male", 18,180 ); 38 39 p1.sayHi (); 40 System. out. println ("23 + 45 =" + p1.doAdd (23, 45); 41 p1.gaiMingZi ("Li Si"); 42 System. out. println ("Hello everyone, I am:" + p1.name); 43 System. out. personal information of println (p1.name + ":" + p1.toString (); 44} 45 46 @ Override47 public String toString () {48 return "[name =" + name + ", sex = "+ sex +", age = "+ age +" years old, height = "+ height +" cm] "; 49}

Running result:

 

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.