标签:
class Person { private String name; private int age; public void setName(String name){this.name=name;} public void setAge(int age) {this.age=age;} public String getName(){return name;} public int getAge(){return age;} public String getInfo() { return "Name: "+ name + "\n" +"age: "+ age; } } class Student extends Person { private String school; public String getSchool() {return school;} public void setSchool(String school) {this.school =school;} public String getInfo() { return "Name: "+ getName() + "\nage: "+ getAge() + "\nschool: "+ school; } } public class TestOverWrite { public static void main(String arg[]){ Student student = new Student(); Person person = new Person(); person.setName("none"); person.setAge(1000); student.setName("John"); student.setAge(18); student.setSchool("SCH"); System.out.println(person.getInfo()); System.out.println(student.getInfo()); } }
内存分析
class SuperClass { private int n; /* SuperClass() { System.out.println("SuperClass()"); } */ SuperClass(int n) { System.out.println("SuperClass(" + n + ")"); this.n = n; } } class SubClass extends SuperClass { private int n; SubClass(int n) { //super(); System.out.println("SubClass(" + n + ")"); this.n = n; } SubClass() { super(300); System.out.println("SubClass()"); } } public class TestSuperSub { public static void main(String arg[]) { //SubClass sc1 = new SubClass(); SubClass sc2 = new SubClass(400); } }
练习1
练习2
public class TestToString { public static void main(String[] args){ Dog d = new Dog(); System.out.println("d:="+d); } } class Dog { public String toString(){ return "I‘m a cool Dog!"; } }
public class TestEquals { public static void main(String[] args){ Cat c1 = new Cat(1,2,3); Cat c2 = new Cat(1,2,3); System.out.println(c1 == c2); System.out.println(c1.equals(c2)); //重写之前同上面一样 } } class Cat { int color; int height, weight; public Cat(int color, int height, int weight){ this.color = color; this.height = height; this.weight = weight; } public boolean equals(Object obj){ if(obj == null) return false; else{ if(obj instanceof Cat){ Cat c = (Cat)obj; if(c.color == this.color && c.height == this.height && c.weight == this.weight){ return true; } } } return false; } }
标签:
原文地址:http://www.cnblogs.com/gimin/p/4772071.html