夜光精华:Java面向对象编程 学习笔记(二)在校资源

版权声明:Genius https://blog.csdn.net/weixin_41987706/article/details/91428655

夜光序言:

 

 

我觉得生命是最重要的,所以在我心里,没有事情是解决不了的。不是每一个人都可以幸运的过自己理想中的生活,有楼有车当然好了,没有难道哭吗?所以呢,我们一定要享受我们所过的生活

 

 

 

 

 

 

 

 

 

 

正文:类的定义与对象的创建


类的方法

 构造方法

//  夜光:一个计数器类 Counter.java
class Counter               //定义一个名为Counter的类
 
{
 
  int countValue;         //存储当前计数值的成员变量,整型
 
  int increment()         //实现计数器加一功能的成员方法
 
  {
 
    return countValue++;  //返回加1后的计数值
 
  }
 
  int decrement()          //实现计数器减一功能的成员方法
 
  {
 
    return countValue--; //返回减1后的计数值
 
  }
 
  void reset()            //实现清零功能的成员方法
 
  {
 
    countValue=0;        //将计数值置为0
 
  }
}
/* 编写一个测试类 testCounter.java, 测试计数器类运行是否正确 */
public class TestCounter
{
 public static void main(String args[])  //定义main方法,作为程序运行主入口
 {
  Counter c=new Counter();                    //定义一个计数器类的对象
  System.out.println("初始值:"+c.countValue); //输出系统默认属性值
  c.countValue=5;                             //将计数器初始值设为5
  System.out.println("设置一个初始值:"+c.countValue);
  c.increment();                              //调用加一的方法
  System.out.println("自加后:"+c.countValue);
  c.decrement();                               //调用减一的方法
  System.out.println("自减后:"+c.countValue);
  c.reset();                                   //调用清零的方法
  System.out.println("清零后:"+c.countValue);
 }
}
// 夜光

class Student
 
{
 
 String stuName;  //学生姓名
 
 String stuClass;   //学生班级
 
 Student(String m,String s)
 
  {
 
        stuName=m;
 
        stuClass=s;
 
 }
 
 void setClass(String sc )
 
 {
 
     stuClass=sc;
 
 }
 
}
 
public class TestStudent
 
{
 
    public static void main(String args[])
 
    {
 
     Student s1=new Student("A", "软161");
 
     Student s2=new Student("B","软162");
 
     System.out.println(s1.stuName+s1.stuClass);    
 
     System.out.println(s2.stuName+s2.stuClass);
 
     s1.setClass("软件162");
 
    System.out.println(s1.stuName+s1.stuClass);
 
    }
 
}

猜你喜欢

转载自blog.csdn.net/weixin_41987706/article/details/91428655