1、对象属性和方法
class Person{ private String name ; private int age = 1; public void setName(String newName) { name = newName; } public String getName() { return name; } public void setAge(int newage) { if(newage >0 && newage<200) { age = newage; } } public int getAge() { return age; } }
2、构造方法 创建对象
1、无参数
2、有参数
在对象实例化的时候,会调用类的构造方法
构造方法和普通方法区别:
1、构造方法的名称必须和类名一致
2、构造方法没有返回值类型
一个类中没有定义任何的构造方法的话,系统会自动提供一个无参的构造方法
但是如果我们已经有了有参数的构造方法,就不会给我们生成一个无参的构造方法,需要自己设置
并且构造方法可以调用普通方法,并且构造方法之间可以相互调用,但是不能是递归的。
但是普通方法不能调用构造方法;
因为构造方法是用来产生实例化对象的;
class Person{ private String name ; private int age = 1; public Person() { System.out.println("无参数构造方法"); } public Person(String newname,int newage) { setName(newname); setAge(newage); } public void setName(String newName) { name = newName; } public String getName() { return name; } public void setAge(int newage) { if(newage >0 && newage<200) { age = newage; } } public int getAge() { return age; } }
3、this关键字 对象本身
1、this表示当前对象
2、this 调用当前对象属性
3、this调用当前对象方法(普通方法和构造方法)
class Person{ private String name ; private int age = 1; public Person() { System.out.println("无参数构造方法"); } public Person(String newname,int newage) { this(); //调用无参数构造方法,必须在第一行 this.setName(newname); this.setAge(newage); } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setAge(int age) { if(age >0 && age<200) { this.age = age; } } public int getAge() { return this.age; } public void printfthis() { System.out.println("this:"+this); } }
public class helloworld { public static void main(String[] srgs){ Person person1 = new Person(); System.out.println("person:"+ person1); person1.printfthis(); } }
无参数构造方法 person:Person@7f31245a this:Person@7f31245a
4、static关键字 类对象和类方法
1、使用static修饰属性,变为类属性
2、使用static修饰方法
3、理解main方法
另外:1、使用staic修饰的方法,不能调用对象属性和方法;只能在static方法之间调用
2、非static修饰,可以使用static修饰的属性和方法
3、在静态方法中,不能使用this,因为使用static修饰的属性和方法,可以在没有实例化对象的时候使用
class Person{ private String name ; private int age = 1; //类属性,可以直接通过类直接访问 private static String ancestor ="女娲"; public Person() { System.out.println("无参数构造方法"); } public Person(String newname,int newage) { setName(newname); setAge(newage); } public void setName(String newName) { name = newName; } public String getName() { return name; } public void setAge(int newage) { if(newage >0 && newage<200) { age = newage; } } public int getAge() { return age; } //使用类方法来调用类属性 public static String getAncestor() { return ancestor; } //使用类方法来调用类属性 public static void setAncestor(String ancestor){ Person.ancestor = ancestor; } }
public class helloworld { public static void main(String[] srgs){ Person person1 = new Person("张三",18); Person person2 = new Person("李四",20); System.out.println(person1.getAncestor()); System.out.println(person2.getAncestor()); person1.setAncestor("盘古"); System.out.println(person1.getAncestor()); System.out.println(person2.getAncestor()); } }
女娲 女娲 盘古 盘古
5、main方法 程序执行入口
public static void main(String[] srgs){ }