/** * 1、super是一个关键字,全部小写, * 2、super和this对比着学习 * * this: * this只能出现在“实例方法”和“构造方法”中 * this的语法是:“this.”、、“this()” * this不能出现在静态方法中 * this.大部分情况是可以省略的 * this.什么时候不能省略呢:::在区分“局部变量”和“实例变量”的时候不能省略 * public void setName(String name){ * this.name=name; * } * this()只能出现在“构造方法”第一行,通过当前的构造方法去调用“本类”中其他的构造方法,目的是代码复用 * * super: * super只能出现在“实例方法”和“构造方法”中 * * super的语法是:“super.”、、“super()” * * super不能出现在静态方法中 * * super.大部分情况是可以省略的 * * super.什么时候不能省略呢:::子类和父类中有相同的属性,并且想在子类中访问父类的属性,super.不能省略 * * super()只能出现在“构造方法”第一行,通过当前的构造方法去调用“父类”中的构造方法, * 目的是:代码复用(创建子类对象的时候先初始化父类特征) * super.不近可以访问属性,也可以访问方法 *3、super() * 表示通过子类的构造方法调用父类的构造方法 * 模拟现实世界中的这种场景:::要想有儿子现要有父亲 * *4、重要结论::: * 当一个方法的第一行:: * 既没有this()又没有super()的话,默认会有一个super() * 表示通过当前子类的构造方法去调用父类的无参数构造方法 * 所以必须保证父类的无参数构造方法必须是存在的 *5、this()和super()不能共存,都只能出现在第一行 */
public class Super {
public static void main(String[] args){
//创建子类的对象
new B();//A类的无参构造方法 B类的无参构造方法
}
}
class A{
public A(){
System.out.println("A类的无参构造方法");
}
}
class B extends A{
public B(){
super();
System.out.println("B类的无参构造方法");
}
}
--------------------------------------------------------------------------------------------------------------------------------
public class SUPer {
public static void main(String[] args){
CreditAccount ca1=new CreditAccount();
System.out.println(ca1.getActno()+","+ca1.getBalance()+","+ca1.getCredit());
CreditAccount ca2=new CreditAccount("78961",122.00,0.99);
System.out.println(ca2.getActno()+","+ca2.getBalance()+","+ca2.getCredit());
}
}
//私有的属性只能在本类中访问
//账户类
class Account{
private String actno;
private double balance;
public Account() {
}
public Account(String actno, double balance) {
this.actno = actno;
this.balance = balance;
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
//信用账户
class CreditAccount extends Account{
private double credit;
public CreditAccount() {
}
public CreditAccount(String acton,double balance,double credit){
/**
* 私有属性只能在本类中访问
this.acton=acton;
this.balance=balance;
*/
//以上两行代码可以在恰当的地方使用 super(acton,balance);
super(acton,balance);
this.credit=credit;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
}
public class SuPer {
//实例方法
public void doSome(){
System.out.println(this);
//System.out.println(super.);
// System.out.println(super);
}
public static void main(String[] args){
SuPer s=new SuPer();
s.doSome();
}
}