作者:金良([email protected]) csdn博客:http://blog.csdn.net/u012176591
package bupt.xujinliang.supersample; public class SuperSample { public static void main(String[] args) { Teacher john = new Teacher("john",34,"male",3000); } } class Person { private String name; private int age; private String gender; public Person() { System.out.println("无参的构造方法"); } public Person (String name,int age,String gender) { System.out.println("有参数的构造方法"); this.name = name; this.age = age; this.gender = gender; } } class Teacher extends Person { private float salary; public Teacher() { } public Teacher(String name,int age,String gender,float salary) { super(name,age,gender);//没有这一行,将调用父类无参构造函数 this.salary = salary; } }
package bupt.xujinliang.supersample; public class SuperSample { public static void main(String[] args) { Teacher john = new Teacher("john",34,"male",3000); john.print(); } } class Person { private String name; private int age; private String gender; public Person() { System.out.println("无参的构造方法"); } public Person (String name,int age,String gender) { System.out.println("有参数的构造方法"); this.name = name; this.age = age; this.gender = gender; } public void print() { System.out.println("name:"+name); System.out.println("age:"+age); System.out.println("gender:"+gender); } } class Teacher extends Person { private float salary; public Teacher() { } public Teacher(String name,int age,String gender,float salary) { super(name,age,gender); this.salary = salary; } public void print() { super.print(); System.out.println("salary:"+salary); } }通过在子类中使用super做前缀可以引用父类中被子类隐藏(即子类中有与父类同名的属性或方法)的属性或被子类覆盖的方法。
package bupt.xujinliang.finalsample; public class FinalSample { public static void main(String[] args) { final TestClass obj = new TestClass(); obj.setNum(10);//对象的属性是可以修改的 obj = new TestClass();//错误,final变量obj不能指向新的对象 } } class TestClass { private int num; public void setNum(int num) { this.num = num; } public int getNum() { return this.num; } }
class Base { public final void method() { } } class Son extends Base { public void method () {//错误,无法重写父类的final方法 } }
public final class Base {} class Son extends Base {} //错误,无法继承final类