首页 > 代码库 > JAVA笔记2__类/封闭性/构造方法/方法的重载/匿名对象

JAVA笔记2__类/封闭性/构造方法/方法的重载/匿名对象

public class Main {    public static void main(String[] args) {        Chicken c1 = new Chicken();        Chicken c2 = null;        c1.eat();        System.out.println(c1.age);        c2 = c1;        c2.eat();    }}class Chicken{    int color;    char sex;    int age;    void eat(){        System.out.println("chikcen1 eat rice.");    }}

 

public class Main {    public static void main(String[] args) {        Person p1 = new Person();        p1.setName("dining");        System.out.println(p1.getName());    }}/** * 封闭性 * 1.把属性设成私有 * 2.为属性提供get/set方法 */class Person{    private String name;    private int age;    public void setName(String name){        this.name = name;    }    public String getName(){        return name;    }}

 

public class Main {    public static void main(String[] args) {        Duck p1 = new Duck("fishDining");        System.out.println(p1.getName());        Duck p2 = new Duck("fishDining2",20);        System.out.println(p2.getName()+" "+p2.getAge());    }}/** * 构造方法 * 1.默认(无参)构造方法:public Duck(){} * 2.带一个(多个)参数的构造方法:Public Duck(String name){this.name=name;} */class Duck{    private String name;    private int age;        //默认构造方法    public Duck(){}    public Duck(String name,int age){        this.name = name;        this.age = age;    }    public Duck(String name){        this.name = name;        System.out.println("I‘m a duck.");    }    public void setName(String name){        this.name = name;    }    public String getName(){        return name;    }    public void setAge(int age){        this.age = age;    }    public int getAge(){        return age;    }}

 

public class Main {    public static void main(String[] args) {        Woman w1 = new Woman();        w1.aa();        w1.aa("keke1");        w1.aa("keke1",21);    }}/** * 方法的重载(方法具有相同名字,但具有不同的参数和不同的定义) */class Woman{    public String name;    public int age;        public void aa(){        System.out.println("aa1");    }    public void aa(String name){        System.out.println("aa2:"+name);    }    public void aa(String name,int age){        System.out.println("aa2:"+name+":"+age);    }}

 

import java.util.Random;import java.util.Scanner;public class Main {    public static void main(String[] args) {        new Woman().aa(); //生成一个匿名对象        new Woman().aa("loveu1");    }}/** * 匿名对象:定义一个没有名称的对象,特点:只能使用一次(直接在堆中开辟内存空间,使用后成为垃圾对象,被GC回收) */class Woman{    public String name;    public int age;        public void aa(){        System.out.println("aa1");    }    public void aa(String name){        System.out.println("aa2:"+name);    }    public void aa(String name,int age){        System.out.println("aa2:"+name+":"+age);    }}

 

JAVA笔记2__类/封闭性/构造方法/方法的重载/匿名对象