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: