1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class Main { public static void main(String[] args) { Person p1 = new Person(); System.out.println(p1.getName()); System.out.println(p1.getAge()); Person p2 = new Person("王八", 99); System.out.println(p2.getName()); System.out.println(p2.getAge()); Student s1 = new Student(); System.out.println(s1.getName()); System.out.println(s1.getAge()); // 向上转型 也可以向下转型,但是向下转型要注意类型,很有可能会报错,可以使用instanceof判断后再向下转型 Person p3 = new Student(); System.out.println(p3.getName()); System.out.println(p3.getAge()); System.out.println(p3 instanceof Student); // true System.out.println(p3 instanceof Person); // true // 多态 p2.run(); //调用Person的run p3.run(); //调用Student的run } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
public class Person { protected String name; private int age; private Book book; //组合 final protected String test = "test"; //不能被修改 // 不能被覆写 final public void test() { System.out.println("test"); } public Person() { // 构造函数可以调用其他的构造函数 // 如果不设置构造方法的话,编译器会自动生成一个空的构造方法 this("张三", 13); } public Person(String name) { this.setName(name); } public Person(String name, int age) { this.setName(name); this.setAge(age); } public String getName() { return name; //this.name(没有歧义的时候this可省略) } public void setName(String name) { this.name = name.trim(); } // 方法重载,利用参数的类型、个数、顺序。方法重载的返回值必须相同 public void setName(String firstName, String lastName) { this.name = firstName.trim() + " " + lastName.trim(); } public int getAge() { return age; } public void setAge(int age) { if(age > 150 || age < 1) { this.age = 18; } this.age = age; } public void run() { System.out.println(this.name + "is run"); } // 重写Object的toString方法 public String toString() { return "Person"; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// 如果不继承任何类,java会自动继承 extends Object public class Student extends Person { public Student() { // 调用父类构造方法 super(); } @Override public void run() { System.out.println("Student:" + this.name + "is run"); } // Override可以让编译器检查是否覆写,这里是重载,会报语法错误 @Override public String run(String test) { return "test"; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// 不能被继承 final public class Book { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |