如何在子类中访问与子类中某个属性同名的祖父属性?

huangapple go评论82阅读模式
英文:

how to access grandparent attribute in the child class with same name as some attribute in child class

问题

I was tinkering with classes and objects, then I had a doubt, since all the non-private
methods and variables/attributes are available to the child class, and if there is any attribute in the parent class with the same name as some attribute in the child class, the it can be accessed using super.attrName. But what if this is the situation in case of multi-level-inheritence, and you want to access the grandparent attribute in the child class, how can it be done. using super.super.attrName gives error.

我的示例代码

public class Main {
    public static void main(String[] args) {
        Abc sahil = new Abc();
        System.out.println(sahil.length);
    }
}

class A {
    int length;

    A() {
        this.length = 1;
    }
}

class Ab extends A {
    int length;
    
    Ab() {
        this.length = 2;
    }
}

class Abc extends Ab {
    int length;

    Abc() {
        this.length = 3;
    }
}
英文:

I was tinkering with classes and objects, then I had a doubt, since all the non-private
methods and variables/attributes are available to the child class, and if there is any attribute in the parent class with the same name as some attribute in the child class, the it can be accessed using super.attrName. But what if this is the situation in case of multi-level-inheritence, and you want to access the grandparent attribute in the child class, how can it be done. using super.super.attrName gives error.

my sample code

public class Main {
    public static void main(String[] args) {
        Abc sahil = new Abc();
        System.out.println(sahil.length);
    }
}

class A {
    int length;

    A() {
        this.length = 1;
    }
}

class Ab extends A {
    int length;
    
    Ab() {
        this.length = 2;
    }
}

class Abc extends Ab {
    int length;

    Abc() {
        this.length = 3;
    }
}

答案1

得分: 0

在Java中,你不能使用super.super,这就是为什么你会得到编译错误的原因。

关键字super用于从直接的父类获取属性和方法,前提是它们从子类中可访问。因此,它只期望方法和属性,而不是关键字。

现在,如果你想要访问顶级父类的属性,最好的方法是创建一个对象并调用属性。另一种方法是在中间父类中创建一系列方法链。你可以在Ab中创建一个方法,返回super.length(A.length),然后在Abc中使用super关键字调用该方法。我不建议这样做,因为随着继承层次中类的数量增加,你将不得不在所有中间类中添加这个方法。

但在正常情况下,我必须提出一个问题。考虑Car(一个类),它有一个gasPedal(一个属性),现在有AudiBentlyHonda,它们都继承自Car。我的问题是,为什么Audi需要来自CargasPedal,当它已经有自己定制的gasPedal呢?

访问超类属性没有任何问题,但我在上面的问题中试图传达的是一个基本的面向对象编程(OOPs)概念。

关于评论的更新

当一个人需要获得他祖父的年龄数据时,你需要在那个人中添加一个新属性grandFatherAge。现在,这个新属性将对他拥有的每个孙子都具有相同的值,因此你可以将其声明为static

class GrandFather {
    int age = 88;
}

class Father extends GrandFather {
    int age = 50;
}

class Son1 extends Father {
    int age = 18;
    static int grandFatherAge;
    
    static {
        grandFatherAge = new GrandFather().age;
    }
}

class Son2 extends Father {
    int age = 15;
    static int grandFatherAge;
    
    static {
        grandFatherAge = new GrandFather().age;
    }
}

class Daughter1 extends Father {
    int age = 21;
    static int grandFatherAge;
    
    static {
        grandFatherAge = new GrandFather().age;
    }
}

class HierarchyManager {
    public static void main(String[] args) {
        System.out.println(Son1.grandFatherAge);
        System.out.println(Son2.grandFatherAge);
        System.out.println(Daughter1.grandFatherAge);
    }
}

我应用了你的“头脑风暴”逻辑,一个人可以直接从他的祖父那里知道他祖父的年龄,不一定需要从他直接的父母那里获得。

英文:

You cannot write super.super in Java, that's why you are getting a compilation error.

The keyword super is used to get the attributes and methods from the immediate parent given that they are accessible from the child. So it expects only methods and attributes and not a keyword.

Now, if you want to access an attribute from the topmost parent, the best thing you can do is create an object and call the attribute. The other way of doing this is by creating a chain of methods in the intermediate parent classes. You can create a method in Ab that returns the super.length (A.length) and call that method from Abc using the super keyword. I won't recommend that because as the number of classes increases in the hierarchy you'll have to add this method in all the intermediate classes.

But, in a normal scenario, I've to ask a question. Consider the Car (a class) which has a gasPedal (an attribute), now there are Audi, Bently, and Honda which inherit from the Car. My question is that why would Audi be requiring the gasPedal from the Car when it has its own custom-designed gasPedal?

There is nothing wrong with accessing the superclass attribute, it is fine, but what I was trying to convey in the above question is a basic OOPs concept.

Update regarding the comment

When a person needs to have data regarding his grandparent's age, you'll need a new attribute in that person, grandFatherAge. Now this new attribute will be having the same value for every grandchildren he has, so you can declare it as static.

class GrandFather {
	
	int age = 88;
}

class Father extends GrandFather {
	
	int age = 50;
}

class Son1 extends Father {
	
	int age = 18;
	static int grandFatherAge;
	
	static {
		
		grandFatherAge = new GrandFather().age;
	}
}

class Son2 extends Father {
	
	int age = 15;
	static int grandFatherAge;
	
	static {
		
		grandFatherAge = new GrandFather().age;
	}
}

class Daughter1 extends Father {
	
	int age = 21;
	static int grandFatherAge;
	
	static {
		
		grandFatherAge = new GrandFather().age;
	}
}

class HierarchyManager {
	
	public static void main(String[] args) {
		
		System.out.println(Son1.grandFatherAge);
		System.out.println(Son2.grandFatherAge);
		System.out.println(Daughter1.grandFatherAge);
	}
}

I applied your "brainstorming" logic, a person can know his grandparent's age directly from his Grandparent, it is not necessary that it needs to come from his direct parent.

答案2

得分: 0

你可以将你的对象转型为你希望引用的类。

"this" 和 "super" 关键字本质上是快捷方式;此外,它们可以解析字段名和局部变量名。

Abc sahil = new Abc();
System.out.println(((A) sahil).length);
System.out.println(((Ab) sahil).length);
System.out.println(sahil.length);
1
2
3
英文:

You can cast your object to the class you're looking to reference.

The this and super keywords are essentially shortcuts; additionally, they can provide resolve for field names and local variable names.

Abc sahil = new Abc();
System.out.println(((A) sahil).length);
System.out.println(((Ab) sahil).length);
System.out.println(sahil.length);
1
2
3

答案3

得分: 0

子类会遮蔽父类的属性。如果你将对象转换为任何父类,适当的值将被提取。

System.out.println(sahil.length); // 3
System.out.println(((Ab)sahil).length); // 2
System.out.println(((A)sahil).length); // 1

英文:

Child classes shadow the property of parent. If you cast the object to any of parent class the appropriate value be extracted.

System.out.println(sahil.length);  // 3
System.out.println(((Ab)sahil).length); // 2
System.out.println(((A)sahil).length); // 1

huangapple
  • 本文由 发表于 2023年5月29日 20:57:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定