Overloading overriding runtime type and object Orientation (1)

Source: Internet
Author: User
Tags abstract inheritance variables string variable throw exception valid access
Loading|object 6) Overloading overriding runtime type and object orientation
Objective 1)
State the benefits of encapsulation in object oriented design and write code that implements tightly encapsulated classes And the relationships "is a" and "has a".

Encapsulation involves hiding data of a class and allowing access only through a public interface.

The separation of interface and implementation makes it easier to modify the code within a class without breaking any othe R code that uses it.

Encapsulation, inheritance, polymorphism are three principal characteristics of Object oriented programming.

Implementing OO Relationships
· ' is a ' relationship is implemented by inheritance (extends keyword)
· The "has a" relationship is implemented by providing the class with its member variables.

Overloading and overriding
· Overloading is an example of polymorphism. (Operational/parametric)
· Overriding is an example of runtime polymorphism (inclusive)
· A method can have the same name as another to the same class, provided it forms either a valid overload or override


Objective 2)
Write code to invoke overridden or overloaded methods and parental or overloaded constructors; and describe the effect of invoking these methods.

Overloading overriding
Signature has to be different.    Just a difference in return type are not enough. Signature has to be the same. (including the return type)
Accessibility may vary freely. Overriding methods cannot is more private than the overridden methods.
Exception list may vary freely.  Overriding methods may isn't throw more checked exceptions than the overridden methods. But can throw no exception.
Just the name is reused. Methods are independent Methods.    Resolved at Compile-time based in method signature. Related directly to Sub-classing. Overrides the parent class method. Resolved at Run-time based on type of object.
Can call all other by providing appropriate argument list. Overriding method can-call overridden-by-super.methodname (), this can is used only to access the immediate SUPER-CL Ass ' s method. Super.super won ' t work. Also, a class outside the inheritance hierarchy can ' t use this technique.
Methods can be static or non-static. Since the methods are independent, it doesn ' t matter. But If two methods have the same signature, declaring one as static and another as Non-static does not provide a valid ove Rload.    It ' s a compile time error. Static methods don ' t participate in overriding, since they are resolved at compile time based on the type of reference Var Iable. A static method in a sub-class can ' t use ' super ' (for the same reason which it can ' t use ' this ' to) Remember that a static Method can ' t being overridden to is non-static and a non-static method can ' t is overridden to being static. In other words, a static method and a Non-static method cannot have the same name and signature (if signatures are NT, it would have formed a valid overload)
There ' s No limit on number of overloaded methods a class can have. Each parent class is overridden at the most once in the any sub-class. (That is, your cannot have two identical methods in the same class)


· Variables can also be overridden, it ' s known as shadowing or hiding. But, member variable references are resolved at Compile-time. So at the runtime, if the class of the object referred by a parent class reference variable, being in fact a has A shadowing member variable, only the parent class variable be accessed, since it ' s already resolved at compile time base D on the reference variable type. Only methods are resolved at Run-time.

public class Shadow {
public static void Main (String s[]) {
S1 S1 = new S1 ();
S2 s2 = new S2 ();

System.out.println (S1.S); Prints S1
System.out.println (S1.gets ()); Prints S1
System.out.println (S2.S); Prints S2
System.out.println (S2.gets ()); Prints S2

S1 = s2;
System.out.println (S1.S); Prints S1, not S2-
Since variable is resolved in compile time
System.out.println (S1.gets ()); Prints S2-
Since method are resolved at run time
}
}

Class S1 {
Public String s = "S1";
Public String GetS () {
return s;
}
}

Class S2 extends s1{
Public String s = "S2";
Public String GetS () {
return s;
}
}
In the above code, if we didn ' t have the overriding GetS () to the sub-class and if we call the "method" from Sub-clas s reference variable, the method would return to the Super-class member variable value. For explanation, and the following point.

· Also, methods Access variables only the ' class of the ' object they belong to. If a sub-class method calls explicitly a super class method, the Super class method always would access the Super-class Var Iable. Super class methods won't access the shadowing variables declared in subclasses because they don ' t know about them. (When a object is created, instances of the all its super-classes are also created.) But the method accessed is again subject to dynamic lookup. It is always decided in runtime which implementation is called. (only static methods are resolved at Compile-time)

public class Shadow2 {
String s = "main";
public static void Main (String s[]) {
S2 s2 = new S2 ();
S2.display (); Produces an output–s1, S2

S1 S1 = new S1 ();
System.out.println (S1.gets ()); Prints S1
System.out.println (S2.gets ()); Prints S1–since Super-class method always
Accesses Super-class variable

}
}

Class S1 {
String s = "S1";
Public String GetS () {
return s;
}
void display () {
System.out.println (s);
}
}

Class S2 extends s1{
String s = "S2";
void display () {
Super.display (); Prints S1
System.out.println (s); Prints S2
}
}

· With OO languages, the class of the object may is known at Compile-time in (by virtue of inheritance). JVM from the "Start is" designed to support OO. So, the JVM insures this method called would be the "real class of" object (not with the variable type declared) . This is accomplished by virtual method invocation (late binding). Compiler would form the argument list and produce one method invocation the Instruction–its job are over. The job of identifying and calling the proper target code is performed by JVM.
· JVM knows about the "variable ' real type" in any time since when it allocates memory to an object, it also marks the type With it. Objects always know ' who they are '. This is the instanceof operator.
· Sub-classes can use super keyword to access the shadowed variables in super-classes. This is technique allows for accessing only the immediate super-class. Super.super is not valid. But casting the "This" reference to classes up above the hierarchy'll do the trick. By this way, variables in super-classes above any level can is accessed from a sub-class, since variables are resolved at Compile time, when we cast the "This" reference to a super-super-class, the compiler binds the Super-super-class variable. But This technique isn't possible with methods since methods are resolved always in runtime, and the method gets called Depends on the type of object and not the type of reference variable. So it isn't at all possible to access a super-super-class a subclass.

public class Shadowtest {
public static void Main (String s[]) {
New Stchild (). Demo ();
}
}
Class Stgrandparent {
Double wealth = 50000.00;
Public double Getwealth () {
System.out.println ("grandparent-" + wealth);
return wealth;
}
}
Class Stparent extends Stgrandparent {
Double wealth = 100000.00;
Public double Getwealth () {
System.out.println ("parent-" + wealth);
return wealth;
}
}
Class Stchild extends Stparent {
Double wealth = 200000.00;

Public double Getwealth () {
System.out.println ("child-" + wealth);
return wealth;
}

public void Demo () {
Getwealth (); Calls Child method
Super.getwealth (); Calls Parent method
Super.super.getWealth (); Compiler error, grandparent method cannot to be accessed
((stparent) this). Getwealth (); Calls child method, due to dynamic method lookup
((stgrandparent) this). Getwealth (); Calls, due to dynamic method
Lookup

System.out.println (wealth); Prints child Wealth
System.out.println (Super.wealth); Prints Parent Wealth
System.out.println ((stparent) (this)). Wealth); Prints Parent Wealth
System.out.println ((stgrandparent) (this)). Wealth); Prints grandparent Wealth
}
}

· A inherited method, which is not abstract on the Super-class, can is declared abstract in a sub-class (thereby making th e sub-class abstract). There is no restriction. In the same token, a subclass can is declared abstract regardless of whether the super-class is abstract or not.
· Private members are not inherited, but they does exist in the sub-classes. Since the private methods are not inherited, they cannot to be overridden. A subclass with the same signature as a private method in the Super-class are essentially a new method, Indepen Dent from Super-class, since the "private method" in the super-class isn't visible in the sub-class.

public class Privatetest {
public static void Main (String s[]) {
New Ptsuper (). hi (); Prints always Super
New Ptsub (). hi (); Prints Super when subclass doesn ' t have Hi method
Prints Sub when subclass has Hi method
Ptsuper sup;
sup = new Ptsub ();
Sup.hi (); Prints Super when subclass doesn ' t have Hi method
Prints Sub when subclass has Hi method
}
}

Class Ptsuper {
public void Hi () {//Super-class implementation always calls superclass Hello
Hello ();
}
private void Hello () {//This method isn't inherited by subclasses, but exists in them.
Commenting out both the "methods in the" subclass show this.
The test would then print "Hello-super" for all three calls
i.e. Always the Super-class implementations are called
System.out.println ("Hello-super");
}
}

Class Ptsub extends Ptsuper {
public void Hi () {//This method overrides Super-class Hi, calls subclass Hello
try {
Hello ();
}
catch (Exception e) {}

}

void Hello () throws Exception {//This is the independent from Super-class hello
Evident from, it's allowed to throw Exception
System.out.println ("Hello-sub");
}
}

· Private methods are not overridden, so calls to private methods are resolved in compile time and don't subject to dynamic me Thod Lookup. The following example.

public class Poly {
public static void Main (String args[]) {
Polya ref1 = new Polyc ();
Polyb Ref2 = (polyb) ref1;

System.out.println (REF2.G ()); This prints 1
If f () is isn't private in polyb, then prints 2
}
}

Class Polya {
private int F () {return 0;}
public int g () {return 3;}
}

Class Polyb extends Polya {
private int F () {return 1;}
public int g () {return f ();}
}

Class Polyc extends Polyb {
public int F () {return 2;}
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.