理解Java的Class类、"this."关键字、Constructor构造器(一)

import java.util.*;

public class BookTest
{
	public static void main(String[] args)
	{
		//Book book = new Book("A Tale of Two Cities", 1895);
		Book book = new Book("A Tale of Two Cities");
		System.out.println(book.title);
		System.out.println(book.pubYear);
		System.out.println(Book.count);
		Book book2 = new Book("War and Peace");
		System.out.println(Book.count); // count 是静态变量,新建book2实类后自动+1
	}
}

class Book
{
	String title;
	int pubYear;
	static int count = 0;
	public Book(String title)
	{
		this(title, -1); //如果没有接收到第二个变量,pubYear自动设为1	
	}

	public Book(String title, int pubYear)
	{
		setTitle(title);
		setPubYear(pubYear);
		++count;
	}
	public void setTitle(String title)
	{
		this.title = title;			
	}


	public void setPubYear(int pubYear)
	{
		this.pubYear = pubYear;			
	}

}
posted @ 2017-06-27 22:02  2021年的顺遂平安君  阅读(343)  评论(0编辑  收藏  举报