قراءة
عرض

The Special Variable "this"

Instance variables and instance methods have simple names. The simple name of such an instance member can be used in instance methods in the class where the instance member is defined. Instance members also have full names, but remember that instance variables and methods are actually contained in objects, not classes. The full name of an instance member has to contain a reference to the object that contains the instance member. To get at an instance variable or method from outside the class definition, you need a variable that refers to the object. Then the full name is of the form variable−name.simple−name. But suppose you are writing the definition of an instance method in some class. How can you get a reference to the object that contains that instance method? You might need such a reference, for example, if you want to use the full name of an instance variable, because the simple name of the instance variable is hidden by a local variable or parameter.
Java provides a special, predefined variable named "this" that you can use for such purposes. The variable, "this", is used in the source code of an instance method to refer to the object that contains the method. This intent of the name, this, is to refer to “this object” the one right here that this very method is in.
If x is an instance variable in the same object, then this.x can be used as a full name for that variable.
If otherMethod() is an instance method in the same object, then this.otherMethod() could be used to call that method.
One common use of this is in constructors. For example:

Example1:
public class Student {
private String name; / / Name of the student .
public Student(String name) {
this.name = name;
} }

In the constructor, the instance variable called name is hidden by a formalter. However, the instance variable can still be referred to by its full name,
this.name. In the assignment statement, the value of the formal parameter, name,
is assigned to the instance variable, this.name. This is considered to be acceptable
style: There is no need to dream up cute new names for formal parameters that are just used to initialize instance variables. You can use the same name for the parameter as for the instance variable.
There are other uses for this. Sometimes, when you are writing an instance
method, you need to pass the object that contains the method to a method, as an actual parameter. In that case, you can use this as the actual parameter.


Shadowed Variables
What happens if an inherited variable has the same name as a variable of the subclass? The variable of the subclass is said to shadow the inherited variable with the same name. The inherited variable is visible in the subclass, yet it cannot be accessed by the same name. But what if you need to use the inherited variable in the subclass; how can it be accessed? The answer is to use the reserved word super. For example, if class B is a subclass of class A, and both contain a variable named common as follows.

Example2:

class A
{
protected int common; ………………. }

class B extends A

{
// shadow the inherited variable common from class A
protected int common;
…………………………… }
Then in class B, the variable common may be referred to by either common or this.common. However, the inherited variable common is referred to by super.common or by ((A)this).common. Notice that the keyword this may be cast to refer to the appropriate class, in this case class A. This technique is useful if you want to refer to a variable in a class beyond (وراء) the immediate superclass higher up the class hierarchy. Although you may refer to shadowed variables by casting an object to the appropriate type, this technique cannot be used to refer to overridden methods.

Overriding Method (ألمهيمنة)

A subclass can override an inherited method by providing a new method declaration that has the same name, the same number and types of parameters and the same result type as the one inherited.
The inherited method is hidden (Shadowed) in the scope of the subclass. When the method is called for an object of the subclass, the overriding method is executed using dynamic binding.
The override method is completely re-declaring the method in the subclass but recognizing that it is a new version of the inherited method, rather than just another method. Constructors cannot be overridden. Overriding should not be confused with overloading.


Example 3:
Consider the following program…what will be the output and why?
public class One {
protected int a,b;
public void set(){
a=50;b=500;}
public void print(){
System.out.println(a+" "+b);}
}
public class Two extends One{
private int x,y;
public void set(){
super.set();
x=100; y=200; }
public void print(){
super.print();
System.out.println(x+" "+y); }
}
public class Main {
public static void main(String[] args) {
Two t=new Two();
t.set(); t.print();}
}


The output :

50 500

100 200
When the super method call for both print and set methods is cancelled the output will be:

100 200

Private methods cannot be overridden, so a matching method declared in a subclass is considered completely separate. Set and print methods in One class are not overridden).

Example4:

public class One {
protected int a,b;
private void set(int a,int b){
this.a=a;this.b=b;}
private void print(){
System.out.println(a+" "+b);}
}
public class Two extends One{
private int x,y;
public void set(int x,int y){
this.x=x;this.y=y; }
public void print(){
set(100,200);
System.out.println(x+" "+y); }}


public class Main {
public static void main(String[] args) {
Two t=new Two();
t.print();} }

The output:

100 200

If we override the set method and set the modifier to "protected" in sub class while it is public in super class, then the compiler will detect an error.
Access to the overridden method using public, protected or the default if no modifier, must be either the same as that of the super class method or made more accessible (change it from protected to public). An overriding method cannot be made less accessible (e.g change from public to protected).
Static method cannot be overridden. Instance methods cannot be overridden by static method. The final instance method cannot be overridden (but can still be overridden) also a final static method cannot be re-declared in a subclass( this point will be explained later).

The Special Variable super

Java also defines another special variable, named “super”, for use in the definitions of instance methods (methods within a class).
The variable super is for use in a subclass. Like "this", super refers to the object that contains the method. But it’s forgetful. It forgets that the object belongs to the class you are writing, and it remembers only that it belongs to the superclass of that class. The point is that the class can contain additions and modifications to the superclass. "super" doesn’t know about any of those additions and modifications; it can only be used to refer to methods and variables in the superclass.
Example 5:

public class One {
protected int x,y;
public One(int a,int b){
x=a;y=b;
System.out.println("One"+x+" "+y);}
public One(){
System.out.println("One One");}
}


public class Two extends One{
private int x;
public Two(){
super(3,4);
x=100;
System.out.println("Two"+x+" "+y+" "+super.x);
System.out.println("Two"+this.x+" "+y+" "+super.x); }
}

public class Main {

public static void main(String[] args) {
Two t=new Two(); // TODO code application logic here
}
}

Example 6:

Let’s say that the class you are writing contains an instance method func1() Consider the method call statement super.func1(). Now, super doesn’t know anything about the func1() method in the subclass. It only knows about things in the superclass, so it tries to execute a method named super.fun1() from the superclass. If there is none you’ll get a syntax error.
public class A{
……
public void func1(){……} // if this method is not exists then an error will be detected
……}
public class B extends A {
…….
public void func1(){……}
public void func2(){
super.func1();
func1();

} }
H.W. Can the subclass accesses private methods in supers using super variables or not ?


The reason super exists is so you can get access to things in the superclass that are hidden by things in the subclass. For example, super.x always refers to an instance variable named x in the superclass. This can be useful for the following reason:
If a class contains an instance variable with the same name as an instance variable in its superclass, then an object of that class will actually contain two variables with the same name: one defined as part of the class itself and one defined as part of the superclass. The variable in the subclass does not replace the variable of the same name in the superclass; it merely hides it. The variable from the superclass can still be accessed, using super.
The major use of super is to override a method with a new method that extends the behavior of the inherited method, instead of replacing that behavior entirely. The new method can use super to call the method from the superclass, and then it can add additional code to provide additional behavior.
Lab

public class One {

protected int a,b;
protected void set(int a,int b){
this.a=a;this.b=b;}
protected void print(){
System.out.println(a+" "+b);}
}

public class Two extends One{

private int a,b;
public void set(int a,int b){
this.a=a;this.b=b;
((One)this).a=10;
//or super.a=10;
super.b=20;}
public void print(){
this.set(100,200);
//or set(100,200);
super.print();
System.out.println(a+" "+b);
}}
public class Main {
public static void main(String[] args) {
Two t=new Two();
t.print();}
}
Explain why the output is:


10 20
100 200



رفعت المحاضرة من قبل: HS Alqaicy
المشاهدات: لقد قام 0 عضواً و 82 زائراً بقراءة هذه المحاضرة








تسجيل دخول

أو
عبر الحساب الاعتيادي
الرجاء كتابة البريد الالكتروني بشكل صحيح
الرجاء كتابة كلمة المرور
لست عضواً في موقع محاضراتي؟
اضغط هنا للتسجيل