Java 对象

  • 两个文件调用模式

one.java

 1  package demo;
 2  2 import java.util.Random;
 3  3 import java.util.Scanner;
 4  4 import java.util.Arrays;
 5  5 
 6  6 
 7  7 import com.sun.org.apache.xpath.internal.operations.Bool;
 8  8 //1+2+3=6
 9  9 public class One {
10 10     String name;
11 11     boolean gender;
12 12     int age;
13 13 //    无参数,无返回
14 14     public void eat(){
15 15         System.out.println("name:"+name);
16 16         System.out.println("gender:"+gender);
17 17         System.out.println("age:"+age);
18 18     }
19 19 //有参数,无返回
20 20     public void sleep(int A){
21 21         System.out.println("我在睡觉:"+A+"分钟");
22 22     }
23 23 //    有参数,有返回
24 24     public String drink(String A,int B){
25 25         System.out.println(A+B);
26 26         return A+B;
27 27 
28 28     }
29 29 }
View Code

two.java

 1 package demo;
 2 import java.util.Scanner;
 3 
 4 public class two {
 5     public static void  main(String[] args){
 6         One MyPerson = new One();
 7         System.out.println(MyPerson.age);
 8         MyPerson.eat();
 9 
10     }
11 }
View Code

 

  • 类与对象放在同一个文件夹的模式

one.java

 

 1 package demo;
 2 import java.util.Random;
 3 import java.util.Scanner;
 4 import java.util.Arrays;
 5 
 6 class One2 {
 7     String name;
 8     boolean gender;
 9     int age;
10 //    无参数,无返回
11     public void eat(int a){
12         if(a==0){
13             System.out.println("ok");
14         }else if(a==1){
15             System.out.println("ok-ok");
16             return;
17         }
18         System.out.println("ok-ok-ok");
19     }
20 //有参数,无返回
21     public void sleep(int A){
22         System.out.println("我在睡觉:"+A+"分钟");
23     }
24 //    有参数,有返回
25     public String drink(String A,int B){
26         System.out.println(A+B);
27         return A+B;
28 
29     }
30 }
31 
32 public class One{
33     public static void main(String[] args){
34         One2 obj = new One2();
35         obj.eat(1);
36     }
37 
38 
39 
40 
41 
42 }
View Code

 

  • toString 方法
 1 package demo;
 2 import java.util.Random;
 3 import java.util.Scanner;
 4 import java.util.Arrays;
 5 
 6 class One2 {
 7     String name="jim";
 8     boolean gender;
 9     int age;
10     
11     public String toString(){
12       return name;
13     }
14 
15 }
16 
17 public class One{
18     public static void main(String[] args){
19         One2 obj = new One2();
20         System.out.println(obj);
21     }
22 
23 
24 
25 
26 
27 }
View Code

 

posted @ 2021-04-04 22:47  东方不败--Never  阅读(51)  评论(0编辑  收藏  举报