Hiển thị các bài đăng có nhãn java. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn java. Hiển thị tất cả bài đăng

How to ignore namespace during unmarshalling of XML document?

Step 1: Create a new class extending XMLFilterImpl




import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import org.xml.sax.helpers.XMLFilterImpl;

public class NamespaceFilter extends XMLFilterImpl {

private String usedNamespaceUri;
private boolean addNamespace;

//State variable
private boolean addedNamespace = false;

public NamespaceFilter(String namespaceUri,
boolean addNamespace) {
super();

if (addNamespace)
this.usedNamespaceUri = namespaceUri;
else
this.usedNamespaceUri = "";
this.addNamespace = addNamespace;
}



@Override
public void startDocument() throws SAXException {
super.startDocument();
if (addNamespace) {
startControlledPrefixMapping();
}
}



@Override
public void startElement(String arg0, String arg1, String arg2,
Attributes arg3) throws SAXException {

super.startElement(this.usedNamespaceUri, arg1, arg2, arg3);
}

@Override
public void endElement(String arg0, String arg1, String arg2)
throws SAXException {

super.endElement(this.usedNamespaceUri, arg1, arg2);
}

@Override
public void startPrefixMapping(String prefix, String url)
throws SAXException {


if (addNamespace) {
this.startControlledPrefixMapping();
} else {
//Remove the namespace, i.e. don´t call startPrefixMapping for parent!
}

}

private void startControlledPrefixMapping() throws SAXException {

if (this.addNamespace && !this.addedNamespace) {
//We should add namespace since it is set and has not yet been done.
super.startPrefixMapping("", this.usedNamespaceUri);

//Make sure we dont do it twice
this.addedNamespace = true;
}
}

}



This Filter can add namespace if not present

new NamespaceFilter("http://www.theRDnotes.com/namespaceurl", true);

Or remove any present

new NamespaceFilter(null, false);


Use the aboce filter for unmashling as following

//Prepare JAXB objects
JAXBContext jc = JAXBContext.newInstance("jaxb.package");
Unmarshaller u = jc.createUnmarshaller();

//Create an XMLReader to use with our filter
XMLReader reader = XMLReaderFactory.createXMLReader();

//Create the filter (to add namespace) and set the xmlReader as its parent.
NamespaceFilter inFilter = new NamespaceFilter("http://www.example.com/namespaceurl", true);
inFilter.setParent(reader);

//Prepare the input, in this case a java.io.File (output)
InputSource is = new InputSource(new FileInputStream(output));

//Create a SAXSource specifying the filter
SAXSource source = new SAXSource(inFilter, is);

//Do unmarshalling
Object myJaxbObject = u.unmarshal(source);


Or to marshal the Java object to XML as follows

//Prepare JAXB objects
JAXBContext jc = JAXBContext.newInstance("jaxb.package");
Marshaller m = jc.createMarshaller();

//Define an output file
File output = new File("test.xml");

//Create a filter that will remove the xmlns attribute
NamespaceFilter outFilter = new NamespaceFilter(null, false);

//Do some formatting, this is obviously optional and may effect performance
OutputFormat format = new OutputFormat();
format.setIndent(true);
format.setNewlines(true);

//Create a new org.dom4j.io.XMLWriter that will serve as the
//ContentHandler for our filter.
XMLWriter writer = new XMLWriter(new FileOutputStream(output), format);

//Attach the writer to the filter
outFilter.setContentHandler(writer);

//Tell JAXB to marshall to the filter which in turn will call the writer
m.marshal(myJaxbObject, outFilter);



-------------------------------------------------------------------------------
[Update 1]
If SOAPMessage, !File
Then create InputSource as follows



ByteArrayOutputStream out = new ByteArrayOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(responseMessage.getSOAPBody().extractContentAsDocument()), new StreamResult(out));

InputSource inputSource = new InputSource(new ByteArrayInputStream(out.toByteArray()));

SAXSource source = new SAXSource(inFilter, inputSource);



Source

IDE specific shortcut for sysout


sysout
sysout
If you're using different IDE to develop a program in Java, you might have searched for a short cut key for System.out.println(). I've so far programmed Java using 3 different IDEs
Netbeans, Eclipse, and JDeveloper.
Here the short cuts for System.out.println on each IDE mentioned above







Shortcut on Netbeans
Type sout and press tab key

Shortcut on Eclipse
Type syso and press ctrl+space

Shortcut on JDeveloper
Type sop and press ctrl+enter

Shortcut for InteliJ
Type sout and press tab

Wonder how sysout works? learn here


Enjoy programming...
Please post any other IDE shortcut for same in comments

Specify non-ASCII characters in a file : i18n

You can specify Unicode character with following escape sequence
\u XXXX
where XXXX refer to 4 hexadecimal digits representing value of the UTF-16 code unit.

E.g. a properties file might have the following entries:
s1=hello there
s2=\u3053\u3093\u306b\u3061\u306f

In order to convert a file saved in non-ASCII encoding to ASCII, you can use native2ascii tool, found in <jdk>\bin
non-ASCII
non-ASCII
native2ascii [options] [inputfile [outputfile]]

Description
The Java compiler and other Java tools can only process files which contain Latin-1 and/or Unicode-encoded (\udddd notation) characters. native2ascii converts files which contain other character encodings into files containing Latin-1 and/or Unicode-encoded charaters.

If outputfile is omitted, standard output is used for output. If, in addition, inputfile is omitted, standard input is used for input.

Options : 
-reverse
Perform the reverse operation: convert a file with Latin-1 and/or Unicode encoded characters to one with native-encoded characters.

-encoding encoding_name
Specify the encoding name which is used by the conversion procedure. The default encoding is taken from System property file.encoding. The encoding_name string must be taken from the first column of the table of supported encodings in the Supported Encodings document.

-Joption
Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes.

Source : Here

How to escape apostrophe (') in MySQL ?

Problem : The data with apostrophe  is not getting saved in MySQL database properly.
In my case I was trying to save <John's Car> in the database. But was getting error on executing the update statement.
Java MySQL JDBC
Java MySQL JDBC

Solution : I read some solution like using methods to escape apostrophe. But in the end, as I was coding in Java, what I found the best approach is using PreparedStatement.

When you set data like following, escaping is handled implicitly by Java.



PreparedStatement pstmt = con.prepareStatement("UPDATE CUSTOM_TABLE SET CUSTOM_COLUMN = ?");

pstmt.setString(1, "John's Car");


Did it work for you?

PHP.net compromised


Unless you didn't have any internet access today, you must have heard about the compromise of PHP.net today. An excerpt:

One of the first confirmations that PHP.net is was in fact compromised






Google Safe Browsing warning













You can read the full discussion on whether PHP was compromised or not here:

Statements by PHP.net itself:
I think it's pretty clear by now how it (could have) happened: insertion of a malicious - or change of- a Javascript file on their website.

Let's start with the first entry of infection, most likely userprefs.js on the main page. Some heavily obfuscated Javascript is present, which redirects to either:
Redirects







Here's a Pastebin link containing the modified userprefs.js: http://pastebin.com/yZWxxk2h

After either of those redirects, PluginDetect (which is a legit Javascript library to detect browser plugins) determines your version of Adobe & Java. If you have any of those vulnerable versions installed, you'll get served with several flavors of malware. Your browser will either crash or "hang" for a while.

Interestingly enough, another PluginDetect was also trying to check for vulnerable versions of VLC, SilverLight and Flash.

If you don't have any of these installed, you're possibly being redirected to a website with the text "He took over Russia with a wooden plough, but left it equipped with atomic weapons" (seems to be a letter about Stalin, see here) which contains the following fancy YouTube video:
http://www.youtube.com/watch?v=9Mnmhtr4ThE


Let's move on to the actual payload. Thanks to a blogpost by Barracuda Labs, I was able to download the PCAP file they gathered. 


The PCAP file proved to be very interesting. Besides being able to pull the usual malicious Javascript files, I was able to gather some payloads as well, which aren't very friendly to your machine.

The following malware was seen to be downloaded: Fareit, ZeroAccess (GoogleUpdate/Google Desktop variant), Zeus and even ransomware (unknown) in one instance!

Fareit and Zeus/Zbot have been known for going hand in hand for some time now, see here for an earlier blogpost. When executed, you'll either have to pay up a fine (ransomware), get a rootkit (ZeroAccess) or get your information stolen (Fareit & Zeus). An overview of the information that will be stolen:

Your data being stolen





















I don't need to mention that this is quite bad. Have you visited PHP.net yesterday or today and saw your browser crash? Did you notice any strange behavior? Yes? No? Either way, perform a scan of your machine right away. We'll get back to that though.

MD5s of samples gathered:
c73134f67fd261dedbc1b685b49d1fa4
406d6001e16e76622d85a92ae3453588
dc0dbf82e756fe110c5fbdd771fe67f5
78a5f0bc44fa387310d6571ed752e217
18f4d13f7670866f96822e4683137dd6

Callbacks:
85.114.128.127



Prevention

  • Patch your Java & Adobe or uninstall it if you don't need it.
    Same goes for their browser plugins or add-ons!
  • Keep your browser of choice up-to-date.
  • Install an antivirus and antimalware product and keep it up-to-date & running.
  • Use NoScript in Firefox or NotScripts in Chrome.
  • Block the above IP. (either in your firewall or host file)


Disinfection 


  • Perform a full scan with your installed antivirus and a scan with another antivirus or antimalware product. You can check on VirusTotal which antivirus applications already detect this malware.


Conclusion

  • Every website can be injected with malicious Javascript, even well-known websites!
  • Received a Google Safe Browsing warning? Don't simply ignore it, either look up if anything's known about that website being hacked or if you're not sure, stay away from it for a while. (best case is to contact the site owner as well.)


Generate Java Classes From Xml Response

Today while consuming a REST service of one of my client, I got the response in XML format and what i needed was to generate POJO classes from that response. So I researched and sharing the 2 step way to do that :

1st step : Convert XML --> XSD

2nd step : Convert XSD --> POJO (java classes)

Converting XML --> XSD

I have used trang.jar for this task. Link.

command (usage)
 java -jar trang.jar file.xml file.xsd

Converting XSD --> POJO (java classes)

For this i have used following executable

<JAVA_HOME>\bin\xjc.exe (jdk1.6.0_13 in my case.)

command (usage)

 xjc file.xsd

------------------------------------------------------------------

Sometimes the above command throws an error like following

XJC
XJC















Following command can get you out of the above error or you can use custom bindings.

xjc -XautoNameResolution PurchaseOrders.xsd

Java exploits lurking around

Update - 31/08/2012
Oracle has issued a patch for the exploit. You can download the patch from:

Oracle has also issued an alert concerning this exploit.
---End update


I'm sure everyone has heard about the latest Java exploits lurking around.


I received the following mail recently:


Mail from ADP, which seems to be a payroll/HR outsourcing firm


Example mails:
#1
ADP Funding Notification - Debit Draft

Your Transaction Report(s) have been uploaded to the web site:

https://www.flexdirect.adp.com/client/login.aspx

Please note that your bank account will be debited within one banking

business day for the amount(s) shown on the report(s).

Please do not respond or reply to this automated e-mail. If you have any

questions or comments, please Contact your ADP Benefits Specialist.

Thank You,

ADP Benefit Services



#2

ADP Generated Message: Final Notice - Digital Certificate Expiration

This e-mail has been sent from an automated system. PLEASE DO NOT REPLY. If you have any questions, please contact your administrator for assistance.

---------------------------------------------------------------------
Digital Certificate About to Expire
---------------------------------------------------------------------
The digital certificate you use to access ADP's Internet services is about to expire. If you do not renew your certificate by the expiration date below, you will not be able to access ADP's Internet services.

Days left before expiration: 1
Expiration date: Aug 27 23:59:59 GMT-03:59 2012

--------------------------------------------------------------------
Renewing Your Digital Certificate
---------------------------------------------------------------------
1. Go to this URL: https://netsecure.adp.com/pages/cert/register2.jsp

2. Follow the instructions on the screen.

3. Also you can download new digital certificate at https://netsecure.adp.com/pages/cert/pickUpCert.faces.

---------------------------------------------------------------------
Deleting Your Old Digital Certificate
---------------------------------------------------------------------
After you renew your digital certificate, be sure to delete the old certificate. Follow the instructions at the end of the renewal process.


When clicking on one of the links in the mail, you get redirected to a compromised webpage, which will load the exploit on your system. The exploit kit responsible is Blackhole.

The exploit in question:
CVE-2012-4681


The following file was downloaded:

Pre.jar
Result: 13/42
MD5: 08fd3413aef2012f2b078fa07855e398
VirusTotal Report



Related files:

adb92c406847e55d699d22ccd36e5e25ff32
Result: 2/42
MD5: b97a943420c13a51af37acbfbcd11d48
VirusTotal Report


js.js
Result: 1/42
MD5: f11a182170557829c150617613cfbb6c
VirusTotal Report


I didn't investigate further at the point when I got the mails, but normally a file called updateflashplayer.exe would have been downloaded as well. At time of writing, it is already offline.


Files were hosted on the IP: 209.59.222.146 - IPVoid result
& 209.59.222.174 - IPVoid result



Google Safe Browsing Diagnostic page


The same reported exploit, but different Jar files and droppers:

applet.jar
Result: 25/42
MD5: 4af58300ee5cd6d61a3eb229afe0da9f
VirusTotal Report


hi.exe
Result: 36/42
MD5: 4a55bf1448262bf71707eef7fc168f7d
VirusTotal Report
Anubis Report


mspmsnsv.dll
Result: 24/42
MD5: 2f8ac36b4038b5fd7efad8f1206c01e2
VirusTotal Report


The malware tries to phone home to:
223.25.233.244 - IPVoid result




Prevention

Disable Java in your browser(s) or uninstall if you have no use for it. Brian Krebs has made a nice post on how to disable Java on several platforms & browsers:
How to Unplug Java from the Browser

Specifically for this exploit, you can block the following IP ranges in your Firewall or hostfile:
(or at least block the ones mentioned in this post)
223.25.233.0 --> 223.25.233.255
209.59.222.0 --> 209.59.222.255

There's an excellent post over at DeepEnd Research as well, which includes a workaround and patch (you will need to request this):
Java 7 0-Day vulnerability information and mitigation



Conclusion

Patch your third-party applications. In cases of Java and Adobe, remove them if unneeded.

To test whether your version of Java is out of date and vulnerable you can use:
Zscaler Java test
Is your Java exploitable?
What Version of Java Are You Using?

Use an antivirus which has or uses behavioural technologies and/or exploit prevention.

Delete emails from unknown senders, never click on links in a mail you allegedly get from your bank, from UPS, or in this case ADP. If you happen to have placed an order or a bank transfer of any kind; go to the website directly in your browser, by typing it in manually.

Note that the links to ADP in this post are not malicious, however the URL behind them was. You can verify this by 'hovering' over the URL to check what is really behind.

Use the add-on NoScript (Firefox) or NotScripts (Chrome) to prevent automatic loading of malicious Javascripts.

Download the latest Java updates from here.

Validations in Struts (simply explained)

Validation in struts can be done In two ways
1 manual or classic way
2 automated or declarative way

In the first approach we'll implement validate() method in ActionForm class.
Lets start step wise explanation, by following an Login Form example.

Consider a page named login.jsp with following code
<body>
<form action="login.do">
UserName : <input type="text" name="user">
Password : <input type="password" name="pwd">
<input type="submit" value="Login">
</body>

For the above jsp we have a ActionForm named LoginForm with default implementation of validate and reset method, code is as follows

public class LoginForm extends ActionForm
{
 private String user = null;
 private String pwd = null;
 public String getUser() { return user; }
 public String getPwd() { return pwd; }
 public void setUser(String u) { this.user = u; }
 public void setPwd(String p) { this.pwd = p; }
}

We will not discus any LoginAction class which will be implementing the actual authorization logic because we will not be needing that in our current topic.

Validation in classic approach is done in 3 ways
Implement validate method in ActionForm class i.e. LoginForm in our case.
Write actual error messages in ApplicationResources.properties file
Turn on validation.

1 implementing validate method: validate method is implemented simply by using if-else statements as follows:

public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if(user==null||user.length()<4)
{
    errors.add("user",new ActionError("login.user"));
}
if(pwd==null||pwd.length()<4)
{
   errors.add("password",new ActionError("login.pwd"));
}
return errors;
}

As you have noticed that return type of validate method is ActionErrors, so an object of type ActionErrors is created. By using if-else conditions we can store errors in ActionErrors object

errors.add("user",new ActionError("login.user"));

Note the difference, in above statement errors is of type ActionErrors, and you are passing new object of type ActionError in parameters of add method.

You can think of ActionErrors object i.e. errors in our case as a map in which you are storing individual ActionError objects with the help of a key (first parameter in add method will act as a key.)


2 Writing actual error messages in ApplicationResources.properties file

A property files are used to store parameters which are stored in format of pair of strings, in which one string represent the name i.e. key and other represent value of that parameter.

Property file of our interest in this application is ApplicationResources.properties, which will be used to store actual error messages that will be shown on client browser.

Don't get confused once completed all flow will be clear, just continue reading.

so following is code of property file i am using in this particular example.


login.user=invalid username
login.pwd=invalid password

NOTE: one thing to be noted here is that keys to be used in property file should be same as the string passed to constructor of ActionError, while adding ActionError object.






3 Turning on validations: In order the validate method to be executed, we have to add an attribute to the mapping section of our ActionClass in struts-config.xml, which will be as follows :


<action-mappings>
<action name="loginForm" path="/login" scope="request"
type="net.mshome.firstsruts.actions.LoginAction"
validate="true"
input="./login.jsp" >
<forward name="success" path="./home.jsp"></forward>
<forward name="fail" path="./fail.jsp"></forward>
</action>
</action-mappings>

if we don't set value of validate attribute to true in struts-config, control will be directly transferred to execute method of ActionClass after ActionForm is being populated. But if validate="true", then after populating ActionForm, RequestProcessor will invoke validate method. Validate method in turn will return ActionErrors object, if it is null then RequestProcessor will invoke execute method of ActionClass otherwise if ActionErrors is not null, then control is sent back to client including those error messages.


Displaying Error Messages on jsp

To display errors on your jsp write the following tag in jsp.

<html:errors/>

Above tag will print all the errors on the jsp.







And for displaying errors specifically in relative to input boxes use following tag syntax

<html:errors property="user" /><br>

In above tag property attribute refer to the key, we used to store ActionError object.

i.e.
errors.add("user",new ActionError("login.user"));

so output will be like





Instead of <html:errors /> tag you can also use following tag


<html:messages id="msg" property="password">
<bean:write name="msg" />
</html:messages>


So that was about classic way of implementing validations in struts. but at this point your brain should raise hand asking How Do <html:errors />, <html:messages> tags find messages.
The reason behind this mystery is that struts stores ActionErrors object returned by validate method in request scope as following


request.setAttribute(Globals.ERROR_KEY,errors);


By default, both tags that are <html:errors /> and <html:messages > uses this key to retrieve messages.

Now the question is can we use custom key

Answer is YES !!! we can

Suppose if we want to throw some message to jsp from ActionClass, in that case we will do it like


if(<some condition>)
{
 ActionErrors err= new ActionErrors();
 err.add("FOLLOW", new ActionError("follow.blog"));
 err.add("EMAIL", new ActionError("email.subscribe"));
 request.setAttribute("CUSTOM_KEY", err);
}

and on jsp

<html:errors name="CUSTOM_KEY" />

so the name attribute will be used to mention what to look for in request scope.

!(Ain't Mistake)

This is the section covering the mistakes I did or the errors I faced while giving this topic first try


Error 500: No input attribute for mapping path /login : This error generally comes when no value is specified for the input attribute of action elements in struts-config.xml.

<action name="loginForm" 
path="/login"
scope="request"
type="net.mshome.webapp.actions.LoginAction"
validate="true"
input="./input.jsp" >
<forward name="path1" path="./pass.jsp"></forward>
<forward name="path2" path="./fail.jsp"></forward>
</action>

Struts framework will forward the control to the path specified in input attribute if validation fails i.e. in case the validation in ActionForm class fails, control will not be passed to Action's execute method, rather control will be forwarded to the page specified in input attribute of specified action elements.

Second approach i.e. automated or declarative way coming in couple of days... cheers !!

integer number too large: Java

Java compiler will throw an error saying "integer number too large:"  when you compile the following code



public class Test
{
         public static void main(String a[])
         {
                 int i = 012;
                 int j = 078;    // compiler will complain at this line
                 System.out.println(i);
                 System.out.println(j);
          }
}

Reason behind this is that
A '0' (zero) in front of a number denotes octal number system like 012, 045 ,0xx anything
and octal number system uses digits 0 t0 7, so 8 is out of the range.
same happens with 019 or 048 or anything that is out of octal range.
this is the reason why compiler complains.


Polymorphism and Data Hiding

Polymorphism, one of the pillar of Object oriented programming, means many forms.



There are two types of polymorphism
    Static (don't confuse it with keyword static in java)
    Dynamic or runtime

What is the difference between these two?
(ahem, curtain raising)

Static polymorphism can be considered as concept of overloading.
&
Dynamic polymorphism can be considered as concept of overriding.

Explanation of above mentioned points:
Overloading can be considered as an example of Static polymorphism Overloading means same named methods can act on different signatures.

System.out.println() is perfect example of overloading (applauses), it may take String, Object reference and primitive data types as argument.Fact is that each overloaded method is different and compiler can see this difference at compile time that is why in overloading binding between method definition and method call is done at compile time and it is dependent on reference of class, and we know reference is created at compile time.
Overriding can be considered as an example of Dynamic polymorphism. 
Overriding means adding your own functionality to a method in child class, which comes from parent class.

Now the binding between method definition and method call is done at runtime because it is dependent on object of class and objects are created at runtime.

Consider overriding Object.toString() method and giving your own implementation to it.
Now consider java program that initiates series of objects and call to toString() method.
Compiler does not mind difference in object references.
At runtime only object's toString() implementation can be seen.
That is why they are called runtime or dynamic polymorphism.

Lets clear it with the help of an example :

abstract class Car
{
   public void showBrakeType()
  {
     System.out.println("Default Brakes");
   }
}

class CarManufacturer1 extends Car
{
   public void showBrakeType()
   {
      System.out.println("Drum Brakes");
   }
}

class CarManufacturer2 extends Car
{
   public void showBrakeType()
   {
      System.out.println("Disk Brakes");
   }
}

public class Test1
{
   public static void main(String a[])
   {
      Car c1=new CarManufacturer1();
      Car c2=new CarManufacturer2();
      c1.showBrakeType();
      c2.showBrakeType();
   }
}


Output will be :


Drum Brakes
Disk Brakes

So above example illustrates that at runtime JVM decides which method to invoke depending on the object ,base class is referring to, i.e. in our example, Car type reference ,referring to two different objects, so different methods being called.

This is called Dynamic Polymorphism.
So up to this was about Static & Dynamic Polymorphism
Now moving ahead what if showBrake() method is static ?
Can we override static method ?
Above example will be like :

abstract class Car
{
   public static void showBrakeType()
   {
     System.out.println("Default Brakes");
   }
}

class CarManufacturer1 extends Car
{
   public static void showBrakeType()
   {
      System.out.println("Drum Brakes");
   }
}

class CarManufacturer2 extends Car
{
   public static void showBrakeType()
   {
      System.out.println("Disk Brakes");
   }
}

public class Test1
{
   public static void main(String a[])
   {
      Car c1=new CarManufacturer1();
      Car c2=new CarManufacturer2();
      c1.showBrakeType();
      c2.showBrakeType();
   }
}


This will compile fine. And when we run the above code with static methods output will be

Default Brakes
Default Brakes

What actually happened is that one static method is hiding another static method.

In case of an instance method, JVM actually determine which method to call, by referring to instance of class (object, c1 or c2 in our case).

But in case of static method, compiler or JVM don't expect any instance (object) to invoke static method, even if we supply instance(object), JVM will ignore it.

JVM will confirm class type of reference variable at compile time and using that class type will call the method.

So in our case class type of our reference variable is Car, so Car.showBrakeType() will be called irrespective of that we are supplying any instance or not.

So it means when we say static methods can't be overridden, it actually means even if we code something that looks like overriding static method, still it won't execute like overridden methods.

That is what we call Data Hiding

So in short when we talk about Overriding :

instance method get overridden.
static method get hidden.

One question that can strike your mind (if not then ask yourself) is that

What is the benefit of dynamic polymorphism ?
What is the benefit of making reference type of super class, referring to object of child class ?

Answer is Flexibility. you can make utility method which will accept super class as parameter type, and hence can pass any child class object as parameter while calling that method. So covering future child classes in that utility method also.