Urgent: Question about Censoring and replacing

Hello, guys.
This is my very first time writting a java program. Please tell me what I have done wrong as this is my first time?
My question is to write a program that asks the user for a word to replace in some text, and the word to replace it with. The program then reads a line of text from the user and echoes the line back to screen replacing all occurrences of the first word with the second word. It only replaces the word being censored when it occurs independently in a line (i.e. not as a part of another word).
Like:
Enter word to censor: dumb
Enter word to replace it: xxxxx
Enter line of text to censor:
The guy is dumb but his friend is even dumber.
The guys is xxxxx but his friend is even dumber.
Please look at my code now and tell me what is wrong?
public class censor
   public static void main(String args[])
       String sentence = "Please type a word which you like to censor"
       String ac =  string sentence;
       String[] temp = null;
       temp = sentence.split(" ");
       for (int j = 0; j < temp.length; j++ )
           if (temp[j].equals("bridge"))
               string sentence = "Censored";
           System.out.println(sentence + " " + string sentence);
} Edited by: G on Apr 13, 2008 4:04 AM
Edited by: KevinGupta on Apr 13, 2008 4:05 AM

Hey guys,
I'm getting an error where I have added the "ERROR LINE" next to the line where im getting an error..
What I'm trying to do ?: I'm trying to make it like
Enter word to censor: dumb
Enter word to replace it: xxxxx
Enter line of text to censor: The guy is dumb dumb dumb dumb and his friend is dumber.
So, this code should replace ALL "dumb" with xxxxx NOT the dumber. But when I try to run this code only one dumb changes to xxxx not all ? So, please help on that. Also, this code doesnt work when I try to write " LIke ThaT " It gives me an exception error ?
{color:#ff0000}Look at the error below (underneath the code){color}
import java.util.*;
public class LineCensor
public static void main(String [] args)
System.out.print("Enter a word to censor: ");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
System.out.print("Enter a word to replace it: ");
String wordC = keyboard.nextLine();
System.out.println("Enter line of text to censor: ");
String phrase = keyboard.nextLine();
String wordLowered = word.toLowerCase();
String phraseLowered = phrase.toLowerCase();
int location = phrase.indexOf(word);
String string1 = phraseLowered.substring(location,(location +
wordLowered.length()));
String string2 = phraseLowered.substring(0, location);
String string3 = phraseLowered.substring(location+word.length());
System.out.println(string2+wordC+string3);
string2 = string2.toLowerCase();
for (int i=0; i < phrase.length; i++)
(phrase.equals());                        <-------- ERROR LINE.
phrase = wordC;
System.out.println(+i);
}ERROR:
The error is:
LineCensor.java:28: not a statement
(phrase.equals());
^
1 error ANOTher ErroR
Enter a word to censor: CaT
Enter a word to replace it: xxxx
Enter line of text to censor:
The cAT wAs CuRioUs abOuT otHER CAT's strings
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1932)
at LineCensor.main(LineCensor.java:17) This error is coming up because of lower and high caps typing. This shouldnt be happening no matter how I type the sentence/word.
Please help ?
Edited by: kabootar on Apr 16, 2008 3:20 AM
Edited by: kabootar on Apr 16, 2008 3:21 AM

Similar Messages

  • Question about Find and Replace PL/SQL option in Forms Builder

    Dear All
    I have a small question .
    I am using Find and Replace PLSQ/SQL in forms Builder ( Edit - Find and Replace PLSQL) to search any code in a form.
    Let say I am searching for EMP .
    Then all the places is coming where EMP is used as well as EMPloyee , EMPloyee_Desc tables also coming .
    So is there any way to serach only the EMP part .

    If you look closely to the right of the "Find What" field, you should see a button - "Expression". This allows you to add some logic to your search. Alternatively, depending on how you code, you could just look for spaces. For example, if you are looking for EMP and not EMPLOYEE, search for EMP with a blank space before and after it (assuming you code this way) or use something like this \bEMP\b This would work for me because I code the same way I write sentences - each work is separated by spaces.
    <blockquote> EMPLOYEE := EMP || ' - ID';</blockquote>
    In this example, seaching for EMP with a blank space after would find what I wanted. However, if you only search for a trailing blank, you may end up also finding words like tEMP. This is where have a blank space before each word is helpful.
    Other, more valuable expressions could be written to accomplish your task. Refer to the Forms Builder Online help for more information about using Expressions in the Find and Replace search window.

  • Urgent - Question about logging and debugging.

    Hi,
    I have a question about the logging and debugging supported by
    Weblogic 6.0. From what I understood by reading the documentation
    it has classes e.g. NotCatalogLogger class for logging the information.
    The class has one method callded
    debug() for writing the debugging information. I want to log the
    debug messages only in some situation. Can I control this using
    some property? Because the documentation says that the debug information
    is logged only if application is running in debug mode. Now how
    do I change the mode of an application??
    Thanks and Reagrds,
    Manoj

    Hi,
    I have a question about the logging and debugging supported by
    Weblogic 6.0. From what I understood by reading the documentation
    it has classes e.g. NotCatalogLogger class for logging the information.
    The class has one method callded
    debug() for writing the debugging information. I want to log the
    debug messages only in some situation. Can I control this using
    some property? Because the documentation says that the debug information
    is logged only if application is running in debug mode. Now how
    do I change the mode of an application??
    Thanks and Reagrds,
    Manoj

  • I have an urgent question about my indesign. I had problems with the creative cloude app and then uninstalled it and then installed it again. Now it is not opening and I cannot download it again either. Pls give me help and advice if there is anything I c

    I have an urgent question about my indesign. I had problems with the creative cloude app and then uninstalled it and then installed it again. Now it is not opening and I cannot download it again either. Pls give me help and advice if there is anything I can do to repair it

    Please authorize ADE 3 with same credentials that you used with older version of ADE

  • A question about grub and USB

    Hi All
    I have a quick question about grub and USB that I can't quite find the answer to by searching.   Most of the FAQs discuss booting a full linux dristribution from USB. My situation is this.  I am getting a new computer with two drives, the second will be arch and the first will be Vista (for my wife).  I want the computer to boot the same way that my wife's machine boots at work so I don't want to install grub on the MBR.  So, is there a way to have all of the grub config files and kernels installed on the second drive and simply install to grub boot loader to the MBR of a USB stick?  My goal would be to simply plug the USB stick into the new PC and boot arch from the second drive. 
    Thanks
    Kev

    i cant say for hp's
    havent worked on any in a while
    recent machines have been coupleof dell's , vaio & emachine
    which dells do offer it at least the ones i tried , my laptop does(dell)
    all home pc's are built by me which do offer to boot individual drives
    what hp you getting it may tell in specs
    are both discs sata? if so it might not offer this option with 2 drives of same interface
    check your power supply alot of these preconfigured machines put cheap under reated power supplies in there
    & will burn your motherboard i just replaced PS(250 watt) & mobo(845gvsr) in an emachines <cheap stuff<
    i hope you researched the pc before buying ie : mobo, power supply are the biggest concerns
    i find it much more benificial to build my own machine gives me peace at mind. the cost is sometimes more in $ but not always , your biggest expense is time researching hardware
    if you live in usa the best places to start looking are bensbargains.net & pricewatch.com
    i am not affiliated with either & niether sell the hardware they are just advertisers a place to buy
    for costomized machines that i would trust is unitedmicro.com theyll asemble & test before shipping
    i have gotten 2 machines so far from them with NO PROBLEMS with hardware (knock knock)
    you may want to consider this in your next venture for pc

  • Three questions about Java and Ftp

    Hello, i've the following questions about Java and Ftp:
    1- .netrc file is in $HOME directory but i can't access to this directory from java code. The following line producesan Exception (directory doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");
    2- .netrc file must have the following permissions: -rw- --- --- but when i create the .netrc file the following permissions are on default: -rw- r-- r--, how can i change this permissions? (In java code, i can't use chmod.....)
    3- Are there any way to pass parameters to a .netrc file? If i get to do this i needn't change the permissions because i can't modify or create/destroy this file.
    Thanks in advanced!!!
    Kike

    1- .netrc file is in $HOME directory but i can't
    access to this directory from java code. The
    following line producesan Exception (directory
    doesn't exists)
    FileWriter file = new FileWriter ("$HOME/.netrc");$HOME would have to be replaced by a shell, I don't
    think you can use it as part of a legal path.
    Instead, use System.getProperty("user.home");
    Ok, thanks
    2- .netrc file must have the followingpermissions:
    -rw- --- --- but when i create the .netrc file the
    following permissions are on default: -rw- r--r--,
    how can i change this permissions? (In java code,i
    can't use chmod.....)Yes, you can: Runtime.exec("chmod ...");
    I need to use estrictly the .netrc with -rw- --- --- permissions
    Yes, i can use Runtime.exec ("chmod ..."); but i don't like very much this solution because is a slow solution, am i right?
    3- Are there any way to pass parameters to a.netrc
    file? If i get to do this i needn't change the
    permissions because i can't modify orcreate/destroy
    this file.I don't think so. Why do you need the .netrc file in
    Java at all? Writing a GUI frontend?I want to use automatic ftp in a java program and FTP server, the files and path are not always the same, so i can:
    - modify .netrc (for me is the complex option)
    - destroy and create a new .netrc (is easier but i have permissions problem)
    - use .netrc with parameters but i haven't found any help about it
    Thanks for your prompt reply!!!!
    Kike

  • I have a Macbook Pro june 2011... I have 8GB ram but I only have 256mb VRAM... I've read some other questions about this and I realized... Why do I not have 560mb of VRAM since I have 8GB of RAM? Is there any way to get more VRAM to play games on steam?

    I have a Macbook Pro june 2011... I have 8GB ram but I only have 256mb VRAM...
    I've read some other questions about this and I realized... Why do I not have 560mb of VRAM since I have 8GB of RAM?
    Is there any way to get more VRAM to play games on steam?
    I've learned  by reading other topics that I can't upgrade my graphics card on my Macbook Pro because it's soldered into the motherboard or somthing like that, but please tell me if there is any way to get more video ram by chaning some setting or upgrading something else. I'd also like to know why I only have 256MB of VRAM when I have 8GB of RAM, since I have 8GB of RAM I thought I was supposed to have 560mb of VRAM...
    So the two questions are...
    Is there any way to upgrade my VRAM, so that I can play games on steam?
    Why do I only have 256MB VRAM when I have 8GB total RAM?
    Other Info:
    I have a quad core i7 Processor.
    My graphcics card is the AMD Radeon HD 6490M.
    I am also trying to play games on my BOOTCAMPed side of my mac, or my Windows 7 Professional side.
    THANK YOU SO MUCH IF YOU CAN REPLY,
    Dylan

    The only two items that a user can change on a MBP are the RAM and HDD (Retinas not included).  You have what the unit came with and the only way you will be able to change that is to purchase a MBP with superior graphics
    If you are very much into gaming, the I suggest A PC.  They are far superior for that type of application to a MBP.
    Ciao.

  • A few questions about MacBooks and Parallels Desktop.

    I have a few questions about MacBooks and Parallels Desktop.
    1) I understand I need at least 1GB of RAM to run Parallels Desktop but what about the hard drive, is the stock 60GB drive big enough?
    2) Related to question 1, even if it was big enough to allow me to install and run Windows would the 60GB drive be enough if I wanted to install a Linux distribution as well?
    3) This has nothing to do with Parallels Desktop but thought I'd ask it here anyway, do Apple Stores carry just the stock MacBooks, or do they carry other configurations?
    Thanks
    Keith

    1. Depend on how intensive you use that HD for saving data on both Mac OS and XP. For standard installation on both OS X and XP, the space of 60 Gb is enough.
    2. Same answer as no 1. You can install all three on that HD space, but the extra spacce available will be less and less for your data. You can save your data on external or back up on cd/dvd and erase it from the HD to keep the free space.
    Remember to leave at least 2 or 3 Gb for virtual memory usage.
    3. Just call them, maybe they don't have it in store stock, but by appointment they might configure one for you before your pick-up date.
    Good Luck

  • One question about Pricing and Conditions puzzle me for a long time!

    One question about Pricing and Conditions puzzle me for a long time.I take one example to explain my question:
    1-First,my sale order use pricing procedure RVAA01.
    2-Next,the pricing procedure RVAA01 have some condition type,such as EK01(Actual Costs),PR00(Price)....,and so on.
    3-Next,the condition type PR00 define the Access Sequences PR00 as it's Access Sequences.
    4-Next,the Access Sequences PR00 have some Condition tables,such as:
         table 118 : "Empties" Prices (Material-Dependent)
         table 5 : Customer/Material
         table 6 : Price List Type/Currency/Material
         table 4 : Material
    5-Next,I need to maintain Condition tables's Records.Such as the table 5(Customer/Material).I guess the sap would supply one screen for me to input the data of table 5.At this screen,the sap would ask me to select one table,such as table 5.When I select the table 5,the sap would go to the screen to let me input the data of table 5.But when I use the T-CODE VK31 or VK32 to maintain Condition tables's Record,I found it's total different from my guess:
    A-First,I can not found one place for me to open the table,such as table 5,to let me input the data?
    B-Second,For example,when I select the VK31->Discounts/Surcharges->By Customer/Material,the sap show the grid view at the right side.At the each line of the grid view,you need to select the Condition Type at the first field.And this make me confused very much.Why the sap need me to select one Condition Type but not the Condition table?To the normal logic,it ought not to select Condition table but not the Condition Type!
    Dear all,I'm a new one in sd.May be this is a very stupid question.But it did puzzle me for a long time.If any one can  explain this question in detail and let me understand the concept,I will appreciate him/her very much.Thank you.

    Hi,
    You said that you are using the T.codes VK31 or VK32.
    These transaction codes are used to enter condition records for standard condition types. As you can see a grid left side having all the standard condition types like price, discounts, taxes, frieghts.
    Pl check using T.code VK11 OR VK12 (change mode)
    Here you can enter the required condition type, in the intial screen. (like PR00, MWST, K004, K005 .....etc)
    After giving the condition type, press enter or click on Combinations icon on top of the screen. Then you can see all the condition tables which you maintained for that condition type. Like as you said table 118, table 5, table 6 and table 4.
    You can select any table and press enter, then you can go into the screen in which you have all the field cataglogues you maintained for that table. For example you selected combination of Customer/Material (table 5) then after you press enter then you can see customer field on top, and material fields.
    You can give all the required values and save the conditon record.
    Hope this is clear.
    REWARD IF HELPFUL.
    Regards,
    praveen

  • 2 question about GPU and Lens correction ,cs5

    Hi
    i have 2 questions about Gpu and lens correction in Cs5
    1)Filter->lens correction->search online
    i get often and almost every connection time out at the first click on search online , at the second click i get no online profile
    is it normal?
    2) question is about Gpu
    it run faster , but talking about ajustament layer
    like saturation or vibrance for example
    i found with the gpu on , a light slow refresh compared with gpu off
    i have set cache  levels 6 ,history 20
    i guess are the defaul
    well i add a saturation layer and move the saturation slide ,increase o decrease saturation
    with Gpu Off , the changes are immedially , i mean i can see in real time the increase o decrease of saturation
    with Gpu On it takes a few(very few) time more
    again is normal ?
    don't be angry , i'm going to buy cs5 and i'm unsecure ... the price make a big role
    thanks

    For what it's worth, I also see a timeout on the first [ Search Online ] click, after about half a minute delay.  Second click turns up results immediately.  This happens each time Lens Correction is started, even without restarting Photoshop, and in both 32 and 64 bit versions.  Also note that I started with one profile listed by default (though from the wrong camera) for my 40D with 28-135 zoom.
    I alsow noticed that I was seeing progress bar activity in the Lens Correction dialog while I was typing this (even though Lens Correction was NOT the active window) every time I hit the 'L' key.  Strange.
    Windows 7 x64.
    -Noel

  • Basic question about storage and safety in iMovie '11

    A very basic question about storage and safety:
    I want to keep a backup of my raw footage on my external hard drive prior to begin working on the movie in iMovie. I want to do this:
    1. Upload the digital files from my camcorder to my Desktop *(as opposed to iMovie)*
    2. Duplicate that footage/clips.
    3. Put the duplicate clips/footage into a folder labeled with the name of that footage (like "Fun At the Dentist" or "Jimmy Learns How to Yodel").
    4. Drag the folder with the footage/clips into my external hard drive into a pre-existing folder titled "Backups/duplicates of all of my raw footage/clips." This big granddaddy folder will house all of the child folders of different movies.
    5 Then, open up iMovie '11 and import the raw footage/clips from my Desktop rather than from my camcorder.
    6. Then I want to make a duplicate of my finished movie and put it in my external hard drive in a "Finished Movies" folder.
    I know that the original raw unedited footage will always be in iMovies '11 but I want the original to also exist immediately accessible in my external hard drive.
    QUESTION:
    Is this viable? Is it wise? (I know it goes an extra unnecessary step, but aside from that.)
    *Do you have any precautionary advice?* Should I do something in my iMovies '11 preferences? What?
    In earlier years with iMovie '04 or '06 (cannot recall) I made many novice errors and ended up losing audio to my finished movie. I also lost footage.
    This time around with iMovie '11 I don't to make such novice, ignorant errors.
    Thanks so much for any comments to this question.
    -L

    Yes I'm sure it will work great for you.
    The iFrame format is something Apple has come up with. The reason for its existence is unknown to me so I can only speculate. But it seems to me that Apple "invented" this format in order to have devices such as Ipod/Ipad/Iphone/Ixxx create clips that are editable on consumer hardware such as already mentioned devices but also standard Mac computers, without the need for format conversion.
    iMovie converts most input formats during import, which takes a lot of time, and this need for conversion often comes as a surprise to most people new to home video editing.
    iFrame has a resolution of 960x540 which is long way from the common standards of 1920x1080 and 1280x720. If your end target is YouTube however, this may not be too bad though. However if you intend to go with YouTube HD, you may find iFrame footage to look wrong since they are effectively upscaled to a higher resolution.
    Technically iFrame uses the H.264 algorithm, a smaller frame size (960x540) and a rather low compression scheme. This will result in large files, but the plus side is that the files are ready for editing without the need for any conversion and iMovie will natively edit the files.

  • Question about RAC and ASM

    Hi,
    We are thinking about build RAC using ASM for OEM database. It'll have two nodes, oracle 10g and Hitachi san with solaris ( or linux ). I've few questions about RAC and ASM.
    1) Do I need to have ASM instance running on each node ? ( most likely yes... but want to make sure )
    2) can I share oracle_home between ASM instance and database instance ? what is the best choice ?
    3) I'm planning to use shared disks for all files, all databases.... what are the pros/cons ?
    4) what should be the installation procedure ? Meaning, first create ASM instance on each node, then install cluster software, build RAC databases...... can someone explain..
    5) I believe RMAN is the only option for backup since I'm using ASM, correct ?
    I'm a newbie to RAC and ASM..
    Thanks,

    user4866039 wrote:
    1) Do I need to have ASM instance running on each node ? ( most likely yes... but want to make sure )yes.
    2) can I share oracle_home between ASM instance and database instance ? what is the best choice ?in 10g you can, in 11gr2 you cannot. and it might be better to seperate them because it will give you more flexibility with patching.
    3) I'm planning to use shared disks for all files, all databases.... what are the pros/cons ?if you share your oracle_home you won't be able to do rolling updates. so i recommend to keep oracle_homes local.
    4) what should be the installation procedure ? Meaning, first create ASM instance on each node, then install cluster software, build RAC databases...... can someone explain..follow the install guide for your respective version. for 10g you'd install clusterware first, then asm and database is last.
    5) I believe RMAN is the only option for backup since I'm using ASM, correct ?pretty much. you could stop your database and dump the raw devices or use asmcmd/asmftp but rman is definitely the best choice
    Bjoern

  • Urgent Question about System Center Server Names and Dashes

    Hey guys I have a quick Urgent question that would be awesome if it happens to get answered quickly :). 
    So in the past we had problems with different server names in components of System Center when setting up different servers.... I never myself saw the errors or what it did, but an absentee colleague did. For example is anything wrong with a name setup like
    xx-scom-01 / xx-scom-02  as compared to the standard scom01 scom02? We have a certain naming convention we are moving to and I wanted to see if this was fixed. I wanted to say it had something to do with the hyphens... anyways any foresight anyone can
    provide would be awesome. Thanks!

    Dashes in the name will work fine.
    Jonathan Almquist | SCOMskills, LLC (http://scomskills.com)

  • Quick (and urgent) Question about Intel G5's

    Just a quick question about the new intel G5's.
    I currently have bunch of software for my PPC G5 which is a Dual 2ghz. Software includes Adobe CS2, Macromedia Studio, Quark 6, etc, etc.
    If I purchase the new intel mac, would I be able to use the same software? or would I be forced to purchase a whole new set of everything I currently have?
    If the software will work on the intel G5, would it perform at the same rate/better than how it performs now on my PPC g5?
    Thanks in advance for any help.

    Rosetta:
    Most of the time you get a real 'hit' when a program first opens that is PPC. Very sluggish. They will require and use more memory than otherwise, too.
    Tests from last August aren't as helpful, there have been improvements, letting the Mac Pro pull even further ahead.
    http://www.barefeats.com/quad06.html
    Comparison Mac Models shows scores of all models. So there is 2x as much or more processing power, bandwidth, better video, as well as disk drives. A 'base' configuration would be 4-6GB RAM.
    And there are differences, more than between G4 and G5.
    People with experience would be Mac Pro Discussions
    Don't use Migration Assistant, and upgrade to CS3 etc. reinstall all your applications fresh.
    There are some drivers and plug-ins, that can be problems, and known.
    Mac Pro 2GHz 4GB 10K Raptor RAID Cinema HD   Mac OS X (10.4.9)   WD RE RAID Aaxeon FW800 PCIe MDD-G4 APC RS1500 Vista

  • A question about inheritance and overwriting

    Hello,
    My question is a bit complicated, so let's first explain the situation with a little pseudo code:
    class A {...}
    class B extends A{...}
    class C extends B {...}
    class D extends C {...}
    class E extends B {...}
    class F {
      ArrayList objects; // contains only objects of classes A to E
      void updateObjects() {
        for(int i = 0; i < objects.size(); i++)
          A object = (A) objects.get(i); // A as superclass
         update(A);
      void update(A object) { ... }
      void update(B object) { ... }
      void update(D object) { ... }
    }My question now:
    For all objects in the objects list the update(? object) method is called. Is it now called with parameter class A each time because the object was casted to A before, or is Java looking for the best fitting routine depending on the objects real class?
    Regards,
    Kai

    Why extends is evil
    Improve your code by replacing concrete base classes with interfaces
    Summary
    Most good designers avoid implementation inheritance (the extends relationship) like the plague. As much as 80 percent of your code should be written entirely in terms of interfaces, not concrete base classes. The Gang of Four Design Patterns book, in fact, is largely about how to replace implementation inheritance with interface inheritance. This article describes why designers have such odd beliefs. (2,300 words; August 1, 2003)
    By Allen Holub
    http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html
    Reveal the magic behind subtype polymorphism
    Behold polymorphism from a type-oriented point of view
    http://www.javaworld.com/javaworld/jw-04-2001/jw-0413-polymorph_p.html
    Summary
    Java developers all too often associate the term polymorphism with an object's ability to magically execute correct method behavior at appropriate points in a program. That behavior is usually associated with overriding inherited class method implementations. However, a careful examination of polymorphism demystifies the magic and reveals that polymorphic behavior is best understood in terms of type, rather than as dependent on overriding implementation inheritance. That understanding allows developers to fully take advantage of polymorphism. (3,600 words) By Wm. Paul Rogers
    multiple inheritance and interfaces
    http://www.javaworld.com/javaqa/2002-07/02-qa-0719-multinheritance.html
    http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html
    http://www.artima.com/intv/abcs.html
    http://www.artima.com/designtechniques/interfaces.html
    http://www.javaworld.com/javaqa/2001-03/02-qa-0323-diamond_p.html
    http://csis.pace.edu/~bergin/patterns/multipleinheritance.html
    http://www.cs.rice.edu/~cork/teachjava/2002/notes/current/node48.html
    http://www.cyberdyne-object-sys.com/oofaq2/DynInh.htm
    http://www.gotw.ca/gotw/037.htm
    http://www.javajunkies.org/index.pl?lastnode_id=2826&node_id=2842
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=001588
    http://pbl.cc.gatech.edu/cs170/75
    Downcasting and run-time
    http://www.codeguru.com/java/tij/tij0083.shtml
    type identification
    Since you lose the specific type information via an upcast (moving up the inheritance hierarchy), it makes sense that to retrieve the type information ? that is, to move back down the inheritance hierarchy ? you use a downcast. However, you know an upcast is always safe; the base class cannot have a bigger interface than the derived class, therefore every message you send through the base class interface is guaranteed to be accepted. But with a downcast, you don?t really know that a shape (for example) is actually a circle. It could instead be a triangle or square or some other type.
    To solve this problem there must be some way to guarantee that a downcast is correct, so you won?t accidentally cast to the wrong type and then send a message that the object can?t accept. This would be quite unsafe.
    In some languages (like C++) you must perform a special operation in order to get a type-safe downcast, but in Java every cast is checked! So even though it looks like you?re just performing an ordinary parenthesized cast, at run time this cast is checked to ensure that it is in fact the type you think it is. If it isn?t, you get a ClassCastException. This act of checking types at run time is called run-time type identification (RTTI). The following example demonstrates the behavior of RTTI:
    //: RTTI.java
    // Downcasting & Run-Time Type
    // Identification (RTTI)
    import java.util.*;
    class Useful {
    public void f() {}
    public void g() {}
    class MoreUseful extends Useful {
    public void f() {}
    public void g() {}
    public void u() {}
    public void v() {}
    public void w() {}
    public class RTTI {
    public static void main(String[] args) {
    Useful[] x = {
    new Useful(),
    new MoreUseful()
    x[0].f();
    x[1].g();
    // Compile-time: method not found in Useful:
    //! x[1].u();
    ((MoreUseful)x[1]).u(); // Downcast/RTTI
    ((MoreUseful)x[0]).u(); // Exception thrown
    } ///:~
    As in the diagram, MoreUseful extends the interface of Useful. But since it?s inherited, it can also be upcast to a Useful. You can see this happening in the initialization of the array x in main( ). Since both objects in the array are of class Useful, you can send the f( ) and g( ) methods to both, and if you try to call u( ) (which exists only in MoreUseful) you?ll get a compile-time error message.
    If you want to access the extended interface of a MoreUseful object, you can try to downcast. If it?s the correct type, it will be successful. Otherwise, you?ll get a ClassCastException. You don?t need to write any special code for this exception, since it indicates a programmer error that could happen anywhere in a program.
    There?s more to RTTI than a simple cast. For example, there?s a way to see what type you?re dealing with before you try to downcast it. All of Chapter 11 is devoted to the study of different aspects of Java run-time type identification.
    One common principle used to determine when inheritence is being applied correctly is the Liskov Substitution Principle (LSP). This states that an instance of a subclass should be substitutible for an instance of the base class in all circumstances. If not, then it is generally inappropriate to use inheritence - or at least not without properly re-distributing responsibilities across your classes.
    Another common mistake with inheritence are definitions like Employee and Customer as subclasses of People (or whatever). In these cases, it is generally better to employ the Party-Roll pattern where a Person and an Organization or types of Party and a party can be associated with other entities via separate Role classes of which Employee and Customer are two examples.

Maybe you are looking for

  • Depreciation for an Asset

    Hi Gurus, How can make a capitalised asset not depreciate or put the depreciation on hold for a year but the asset still forms part of my asset register. Please advise, Thanks, Themba

  • ITunes won't join CD tracks

    I am using iTunes 10.1.1.4. I have previously been able to join tracks of audiobook CDs but all of a sudden, the option to join CD tracks is constantly greyed out. anybody know why this is happening, or do I have to reinstall iTunes?

  • Compression settings not working on Premiere Pro CC

    I am a freelance editor working for a satellite delivery company. They have specific settings they require for their uplink signals. These setting have worked great on CS5, CS6 and CC2014. However the company is now using CC and these settings create

  • Command + F

    When I do a Command + F a window pops up to allow me to search. Is there a way to change the defaults in this window? Currently the window comes up Search: This Mac Contents Kind is any Would like to change default to Search: This Mac File Name syste

  • Mess up "Mail, Contacts, Calenders", but good! Described in 1st comment below. Basic computer idiot!

    I went in my settings under "Mail, Contacts,Calendars", and I basically made a MESS! Can't get it back to the way it was, was initially using my free Shaw account, now all I get is Now mail all messed up and can't get it back to what it was, just a t