zoukankan      html  css  js  c++  java
  • Java基础16-类与对象

    1.如何创建一个类

     1 public class Person{
     2     //属性
     3     String name;
     4     String genter;
     5     int age;
     6     //方法
     7     public void eat(){
     8         System.out.println("我会吃饭");
     9     }
    10 }

    2.使用创建类的步骤

      必须使用new关键字创建一个对象

      使用对象属性(对象名.成员变量)

      使用对象方法(对象名.方法名)

      同一个类的每个对象有不同的成员的成员变量的存储空间

      同一个类的每个对象共享该类的方法

     1 public class Test1{
     2     public static void main(String[] args){
     3         //创建Person对象
     4         Person one=new Person();
     5         one.name="小明";
     6         System.out.println(one.name);
     7         one.eat();
     8         
     9         Person two=new Person();
    10         System.out.println(two.name);
    11         two.eat();
    12     }
    13 }

    3.内存分析

     4.定义类的方法时有三种情况,无参无返回、有参无返回、有参有返回

     1 public class Person{
     2     //属性
     3     String name;
     4     String genter;
     5     int age;
     6     //方法 无参无返回
     7     public void eat(){
     8         System.out.println("我会吃饭");
     9     }
    10     //有参无返回
    11     public void sleep(String s){
    12         System.out.println("在"+s+"睡觉");
    13     }
    14     //有参有返回
    15     public int getAge(int a){
    16         return a;
    17     }
    18 }
     1 public class Test1{
     2     public static void main(String[] args){
     3         //创建Person对象
     4         Person p1=new Person();
     5         p1.name="小明";
     6         System.out.println(p1.name);
     7         //调用无参无返回方法
     8         p1.eat();
     9         //调用有参无返回方法
    10         p1.sleep("地上");
    11         //调用有参有返回方法
    12         int age=p1.getAge(18);
    13         System.out.println(age);
    14         
    15         Person p2=new Person();
    16         System.out.println(p2.name);
    17         p2.eat();
    18         p2.sleep("床上");
    19         int age2=p2.getAge(25);
    20         System.out.println(age2);
    21         
    22     }
    23 }
  • 相关阅读:
    python中zip函数
    python中创建列表、元组、字符串、字典
    python中enumerate函数
    python中字符串的拼接
    python中格式化浮点数及科学计数法
    python中tuple函数
    python中可迭代对象的排序
    python中变量类型转换
    python中可迭代对象反转
    python中list函数
  • 原文地址:https://www.cnblogs.com/shenhainixin/p/9975637.html
Copyright © 2011-2022 走看看