构造方法的定义
- 构造方法名称必须与类名称保持一致。
- 构造方法不允许设置任何的返回值类型,即:没有返回值定义。
- 构造方法是在使用关键字new实例化对象的时候自动调用的。
- 简单类的定义方法
class Person{ private String name; private int age; public Person(){ this("dog",18); } public Person(String name){ this(name, 28); } public Person(String name, int age){ this.name = name; this.age = age; }
public void getInfo (){25 collapsed lines
System.out.println("my name is "+this.name+",my age is "+this.age) ; }
public void setName(String name){ this.name = name; }
public void setAge(int age){ this.age = age; }
public String getName(){ return this.name; } public Number getAge(){ return this.age; }}
public class JavaDemo { public static void main( String args []){ Person per = new Person("ccc",25); per.getInfo(); }}带静态变量static的类构造
class Book{ private String name; private int bid ; private double price ; private static int count = 0; public Book(){ } public Book(String name , double price){ this.bid = count++; this.name = name; this.price = price; }
public String getInfo(){ return "book name:"+this.name+",book price:"+this.price;13 collapsed lines
} public static int getCount (){ return count; }}public class JavaDemo { public static void main(String args []){ Book b3 = new Book("html", 100.00); Book b2 = new Book("html2", 222200.00); System.out.println(b3.getInfo()); System.out.println(Book.getCount()); }}简单类的练习
class User{ private String name; private int no;
public User(String name , int no){ this.name = name; this.no = no; }
public void setName(String name ){ this.name = name; }
public void setNo (int no ){ this.no = no;31 collapsed lines
}
public String getName (){ return this.name; }
public int getNo(){ return this.no; }
public String getInfo(){ return "my name is "+ this.name+",my no is "+this.no; }}
public class Demo { public static void main(String args []){ User user1 = new User("cirry", 1); User user2 = new User("winnie", 2); System.out.println(user1.getInfo()); System.out.println(user2.getInfo());
user1.setName("cirry666"); System.out.println(user1.getNo()); System.out.println(user1.getInfo());
user2.setNo(2); System.out.println(user2.getInfo());
}}