super
super()在构造方法中的使用
在构造方法的第一行如果没有this()那么就会调用super()
super()执行会调用父类的无参构造
//super()在构造方法中有什么用?
public class blogTest {
public static void main(String[] args) {
B b1 =new B();
B b2 =new B(2);
/*A的无参构造执行
B的无参构造执行
A的无参构造执行
B的有参构造执行*/
}
}
class A{
//A的无参构造
public A(){
System.out.println("A的无参构造执行");
}
//A的有参构造
public A(int i){
System.out.println("A的有参构造执行");
}
}
class B extends A{
public B(){
System.out.println("B的无参构造执行");
}
public B(int i){
System.out.println("B的有参构造执行");
}
}
super(参数)怎么执行?
package caopeng.javase.blogTest;
//super()在构造方法中有什么用?
public class blogTest {
public static void main(String[] args) {
B b1 =new B();
B b2 =new B(2);
/*A的有参构造执行
B的无参构造执行
A的无参构造执行
B的有参构造执行*/
}
}
class A{
//A的无参构造
public A(){
System.out.println("A的无参构造执行");
}
//A的有参构造
public A(int i){
System.out.println("A的有参构造执行");
}
}
class B extends A{
public B(){
super(1);
System.out.println("B的无参构造执行");
}
public B(int i){
System.out.println("B的有参构造执行");
}
}
再来看两个例子
理解一下 this. 和super. 的区别
public class blogTest {
public static void main(String[] args) {
Vip vip =new Vip("张三");
vip.shopping();
}
}
class Customer{
//封装
private String name;
//无参构造
public Customer(){
}
//有参构造
public Customer(String name){
this.name =name;
}
//setter and getter
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
class Vip extends Customer{
//构造方法
public Vip(){
}
public Vip(String name){
super(name);
}
//方法
public void shopping(){
System.out.println(this.getName() + " is shopping");
System.out.println(super.getName() + " is shopping");
System.out.println(getName() + " is shopping");
}
}
运行结果:
张三 is shopping
张三 is shopping
张三 is shopping
但是如果代码变成这样呢?
public class blogTest {
public static void main(String[] args) {
Vip vip =new Vip("张三");
vip.shopping();
}
}
class Customer{
//封装
private String name;
//无参构造
public Customer(){
}
//有参构造
public Customer(String name){
this.name =name;
}
//setter and getter
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
class Vip extends Customer{
//同名变量
private String name;
//构造方法
public Vip(){
}
public Vip(String name){
super(name);
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
//方法
public void shopping(){
System.out.println(this.getName() + " is shopping");
System.out.println(super.getName() + " is shopping");
System.out.println(getName() + " is shopping");
}
}
运行结果变成
null is shopping
张三 is shopping
null is shopping
两个代码运行起来不一样的原因是
可以从内存图中看出
访问父类的方法:
public class blogTest {
public static void main(String[] args) {
Cat cat = new Cat();
cat.test();
}
}
class Animal{
public void move(){
System.out.println("Animal is moving");
}
}
class Cat extends Animal{
public void move(){
System.out.println("Cat is moving");
}
public void test(){
this.move();
super.move();
move();
}
}
运行结果:
Cat is moving
Animal is moving
Cat is moving