英文:
Is this variable Overriding
问题
/*package whatever //do not write package name here */
//package inheritance;
import java.util.*;
import java.lang.*;
class Dog{
public static String Name = "Miku";
public void bark(){
System.out.println("The Dog is Barking"); //class methods
}
public void run(){
System.out.println("The Dog is runing"); //class methods
}
}
class Hound extends Dog{
//Overridden method bark()
public void bark(){
super.bark();
Name = "Doggo";
System.out.println("The Hound " + this.Name + " is barking");
System.out.println("The Hound " + super.Name + " is barking");
}
}
public class Test6{
public static void main(String Args[]){
Hound H = new Hound();
H.bark();
}
}
输出结果为:
The Dog is Barking
The Hound Doggo is barking
The Hound Doggo is barking
英文:
/*package whatever //do not write package name here */
//package inheritance;
import java.util.*;
import java.lang.*;
class Dog{
public static String Name="Miku";
public void bark(){
System.out.println("The Dog is Barking"); //class methods
}
public void run(){
System.out.println("The Dog is runing"); //class methods
}
}
I have not declared variable "Name" how is it able to overwrite super class variable.
Plaese explain how is the variable "Name" working here
class Hound extends Dog{
//Overridden method bark()
public void bark(){
super.bark();
Name="Doggo";
System.out.println("The Hound " +this.Name +" is barking");
System.out.println("The Hound " +super.Name +" is barking");
}
}
public class Test6{
public static void main(String Args[]){
Hound H=new Hound();
H.bark();
}
}
The output to the code is
The Dog is Barking
The Hound Doggo is barking
The hound Doggo is barking
答案1
得分: 0
它没有被覆盖,而是被子类 Hound 继承。
根据定义,“静态方法和变量会从超类继承到子类,只要该方法对子类是可访问的。我的意思是,如果子类(子类)位于不同的包中,只要在超类中声明为 public 或 protected 的方法,它将被继承到子类中。”
因此,您的 Hound 类可以访问变量 name,而且它不是 final 的,因此该值可以通过继承类 Hound 的方法进行更改。
英文:
it is not overridden. it is inherited by the child class Hound.
By the definition "Static methods and variables are inherited from super-class to subclass, as long as the the method is accessible to the subclass. By that I mean if the child-class(subclass) is in different package then, as long as the method is declared public or protected in the superclass it will be inherited in the subclass."
so your hound class has access to the variable name and it is not final so the value can be changed by the methods of the inheriting class hound.
答案2
得分: 0
这并非覆盖重写。
因为它是公开的,且非终态,你可以访问以修改它。
由于它是静态的,实际上是从相同的内存空间中更改了父级的值。
更多详情,请参考此链接。
英文:
It is NOT overriding. <br>
Since it is public and NOT final, you have access to modify it. <BR>
Since it is static, you are actually changing the parent value from the same memory space.
For more details, follow this link.
专注分享java语言的经验与见解,让所有开发者获益!
评论