类和对象

Java中类和对象的创建以及运用

package first;
public class first {

    public static class Address{//定义一个住址类
        //城市
        String city;
        //街道
        String street;
        //邮编
        String zipcode;
    }

    public static class User{//定义一个用户类
        //用户编号
        int no;
        //用户名
        String name;
        //家庭住址
        Address addr;
    }

    public static void main(String[] args){

        User us1 =new User();
        us1.addr=new Address();

        us1.no=1;
        us1.name="张三";
        us1.addr.city="北京";
        us1.addr.street="北三环";
        us1.addr.zipcode="123456";

        System.out.println("用户个人信息:");
        System.out.print("  姓名:"+us1.name);
        System.out.print("  号码:"+us1.no);
        System.out.print("  城市:"+us1.addr.city);
        System.out.print("  街道:"+us1.addr.street);
        System.out.print("  邮编:"+us1.addr.zipcode);
    }
}

 

 

类和对象类似于c语言中的结构体

注意通过new创建一个新的对象

如:

User us1 =new User();
us1.addr=new Address();

  

 

posted @ 2021-07-15 15:10  琉璃若火  阅读(24)  评论(0)    收藏  举报