java--基本语法2

日期的例子:

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
public class MyDate {
private int day; //
private int month; //
private int year; //
public MyDate( int day, int month, int year){
this .day = day;
this .month = month;
this .year = year;
}

public MyDate(MyDate date) {
this .day = date.day;
this .month = date.month;
this .year = date.year;
}

public int getDay() {
return day;
}

public void setDay( int day) {
this .day = day;
}

public MyDate addDays( int more_days) {
MyDate new_date
= new MyDate( this );
new_date.day
= new_date.day + more_days;
return new_date;
}

public void print() {
System.out.println(
" MyDate: " + day + " - " + month + " - " + year);
}
}

这个类名就是MyDate.MyDate 这个类里面定义了3个属性,4个方法,2个构造函数。

java的类里面有3个东西,看下面:

    class 类名 {
    声明属性;
    声明构造函数;
    声明方法;
    }

 

调用:

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
public class TestMyDate {
public static void main(String[] args) {
MyDate my_birth
= new MyDate( 22 7 1964 ); // 通过第一个构造函数new了一个叫my_birth的对象,并在参数里面赋值

MyDate the_next_week
= my_birth.addDays( 7 ); // 这个对象调用了addDays(int more_days)的方法,赋值给the_next_week的变量
the_next_week.print(); // 调用print()方法
}
}

 

转载于:https://www.cnblogs.com/lovening/archive/2010/08/02/1790622.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值