Inheritance and private instance variables

I've been reading a Java book. It says you should normally make your instance variables private and use getter/setter methods on them, but if you create a superclass, you have to make those variables public (or default?) to inherit them in the subclasses, right? And you can't redefine the variables as private in the subclass, can you?
I'm a little confused on this point. Thanks for any light anyone could shed on this.
=====
Nevermind...I think I figured it out!
Message was edited by:
NovaKane

Thanks to both of you for your responses. I think I've pretty much done what you did, Anan, in this little test program.
public class Animal
   private String name=null;
   public void setName(String n)
      name=n;
   public String getName()
     return name;
   public void makeSound()
public class Dog extends Animal
   public void makeSound()
      if (getName() !=null)
         System.out.println(getName()+" says, \"Bow Wow!\"");
      else
         System.out.println("I don't have a name...but \"Bow Wow!\"");
public class Cat extends Animal
   public void makeSound()
      if (getName() != null)
         System.out.println(getName()+" says, \"Meow!\"");
      else
         System.out.println("I have no name...but, \"Meow!\"");
import java.util.*;
public class Test
   public static void main(String[] vars)
        ArrayList<Animal> animals = new ArrayList<Animal>();
        Animal d = new Dog();
        Animal c = new Cat();
        d.setName("Fido");
        c.setName("Fluffy");
        animals.add(d);
        animals.add(c);
        for (Animal a : animals)
            a.makeSound();
}The "name" instance variable is private, but I can get at it through the getter/setter methods of the superclass, which are public. I should NOT be able to say something like...
d.name="Fido";Right?

Similar Messages

  • Servlets and their instance variables

    I understand that for every request to a servlet, a new thread handles those requests. So it's one request, one thread. But how about instance variables of a servlet class? Are they also one instance variable per thread/request or just like the servlet, one instance?

    hi, its exactly as you expect - one instance at all. all threads are working with one intance. you can indeed finetune the number of instances of a servlet using the
    <load-on-startup/>tag in the web.xml file, but its up to container if multiple thread will be using many instances.
    you can also implement the (deprecated) SingleThreadedModel interface which flags the container not to share that servlet instance to other threads. But this shall not be used in productive environments.
    so its always a good idea to put your business impleementation to another class and only use the servlets to connect your business implementation to http like
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
       new MyBusinessLogic().perform(request.getInputStream(), response.getOutputStream());
    }

  • Design question: When to use instance variables

    Looking for best practice/design advise.
    I am working my way through an exercise where I convert a zip code to a postal barcode (and back), validate the format, and validate/generate a check digit. My code works fine. I posted comments and methods below for reference. In addition to the book I am using, I also read http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html.
    My question is: In designing this class, should I have defined instance variables to hold the generated zipcode, barcode, and checkdigit and then used getter methods to get the zipcode or barcode?
    I planned on creating a user interface to ask for a zipcode or barcode and present a conversion to the user. The only methods that need to be called are "convertBarcodeToZipcode" and "convertZipcodeToBarcode". All the other methods are utility methods. The strings that are returned by these two methods are presented to the user.
    I could, easily enough, create and populate instance variables, but would I keep the return statements as well or remove them?
    Thanks, Mike
    ps: I am self-learning java, so I don't have an instructor to ask. :)
    public class PostalBarCode {
         * Constructor.
         * Set up the barcode ArrayList
        public PostalBarCode() {
                barcodeUnits.add("||:::");
                barcodeUnits.add(":::||");
                barcodeUnits.add("::|:|");
                barcodeUnits.add("::||:");
                barcodeUnits.add(":|::|");
                barcodeUnits.add(":|:|:");
                barcodeUnits.add(":||::");
                barcodeUnits.add("|:::|");
                barcodeUnits.add("|::|:");
                barcodeUnits.add("|:|::");
         * Convert a barcode to a zipcode.
         * Assumes the input format is valid. Validates the check digit
         * @param theBarcode string to be converted
         * @return the zipcode as a String of empty string for error
        public String convertBarcodeToZipcode(String theBarcode) {}
         * Convert the Zipcode to a barcode
         * @param theZipcode string to be converted
         * @return the barcode as a string
        public String convertZipcodeToBarcode(String theZipcode) {}
         * Determines if theString is a barcode
         * @param theString
         * @return true if the input is a barcode, false otherwise.
        public boolean isBarcode (String theString) {}
         * Determines of theString is a zip code
         * @param theString the string to test for 5 digits
         * @return true for a zip code, false otherwise
        public boolean isZipcode (String theString) {}
         * Convert a barcode to a zipcode.
         * Assumes the input format is valid. Validates the check digit
         * @param theBarcode string to be converted
         * @return the zipcode as a String of empty string for error
        public String convertBarcodeToZipcode(String theBarcode) {}
         * Convert the Zipcode to a barcode
         * @param theZipcode string to be converted
         * @return the barcode as a string
        public String convertZipcodeToBarcode(String theZipcode) {}
         * Calculate the check digit from the zipcode
         * @param theZipcode as a String
         * @return the the check digit or -1 for error
        public int calculateCheckDigitFromZipcode(String theZipcode) {}
         * Calculate the check digit from the barcode
         * @param theZipcode as a String
         * @return the the check digit or -1 for error
        public int calculateCheckDigitFromBarcode(String theBarcode) {}
         * Validate the format of the barcode.
         * Should be 6 blocks of 5 symbols each.
         * Also check if frame bars are present and strip them.
         * @param theBarcode
         * @return true for proper format, false for improper format
        public boolean validateBarcodeFormat (String theBarcode){}
        private  ArrayList<String> barcodeUnits = new ArrayList<String>();
    }

    These are just my two cents. The various methods that determine whether something is a zip or bar code can easily remain static. After all, you probably don't want to create an instance and then call something like isValid(), although you could do so. The various other methods could easily be instance methods. You could have a toZipCode() or toBarCode() method in each object to convert from one to the other. I would personally throw something like ValidationException rather than returning -1 for your various check-digit methods.
    - Saish

  • Renaming instance variable VS use of "this."

    Open Topic:
    Do you prefer this code?
    private var _myVar:int;
    public function myClassConstructor(value:int) {
         _myVar = value;
    or this code? (JAVA style)
    private var myVar:int;
    public function myClassConstructor(myVar:int) {
         this.myVar = myVar;
    Discuss the pros and cons, especially if performance is involved.
    You have 10 minutes... I will be collecting the papers

    Bertrand G. wrote:
    So no one is concerned about any performance issues using 'this'... I have seen somewhere that using 'this' in C++ is not as efficient as renaming the variable, because it makes an object instantiation or something like that.
    Most people will go for clarity of purpose in the code in preference to performance, simply because performance is not a critical factor for MOST purposes.
    I personally prefer using this for the setters and getters, this way I can have the same variable name for both the method parameters and the class variable.
    Just my 2 cents...
    I think the usual practice for getters and setters is to have a private variable for the instance variable and to name it with an underscore prefix to indicate that the variable is private. In that way references to the private variable are distinct to the variable name used in the setter and getter. In any event, in my setter I invariably name the parameter with the new value "newValue" or "newWhatever", some people just use "pWhatever" to indicate that variables have been passed as parameters, so the use of "this" is not required.
    I don't see the use of "this" as particularly relevant to performance, or getters and setters, and I would recommend naming private variables with an underscore prefix to indicate the use of a private instance variable, though not everyone follows this convention and may use other conventions, or indeed no convention at all.
    Paul

  • Public instance variable vs. accessor method

    I know some OOP purists believe all instance variables should be private, and if there's a need to view or set the value of these instance variable, public accessor methods need to be created. Data encapsulation is the driving force behind this belief.
    But in Java, it's easy enough to declare an instance variable public thus eliminating the need to write accessor method. What's the rational behind this feature? Is it merely to save developer some time from typing in the accessor methods? Does this reason justify the use of public members?

    I know some OOP purists believe all instance variables
    should be private, ALL? No way!
    and if there's a need to view or
    set the value of these instance variable, public
    accessor methods need to be created. There has to be a reason for any :- public int getMyInt(){ ...
    and in many cases protected or default package is more appropriate
    Data
    encapsulation is the driving force behind this belief.
    Correct , also avoiding multiple instances of member states - very often its a control issue too
    But in Java, it's easy enough to declare an instance
    variable public Yes and its also easy enough to write shittie code too ...
    if an instance variable is public there should be a clear comment explaining why the field has to be public
    thus eliminating the need to write
    accessor method. There's nothing wrong with accessors and mutators - the java language is full if them
    What's the rational behind this
    feature? As you stated encapsulation
    Is it merely to save developer some time
    from typing in the accessor methods? This is a lame reason
    Does this reason
    justify the use of public members?and attract unwanted side effects?
    I also don't like to see (or to write) a huge long list of getters and setters at the bottom of any class file and find it quite ugly - You should use them when you need to, not as a matter of routine.
    Accessor - mutator is a design issue for private instance variables that you wish to keep hidden. Your suggestion to make them all public is also a design issue and if I was to see a long list of public variables at the beginning of a class (unexplained with javadoc comments) I would be very puzzled indeed.
    Eclipse will automate the generation of accessors and mutators for you and also has a refactoring tool too - both are extremely useful

  • Java - Instance variable that can reference an array of integers?

    Hello,
    I have the following question in my assignment:
    Your first task is to declare a private instance variable called cGroups that can
    reference an array of integers. You should then write a constructor for GameN. This should
    take a suitable array as its argument which should be used to initialise cGroups.
    In order to test your code for declaring and initialising cGroups, you should execute
    the following code
    int[] coin = {2, 8, 5};
    GameN aGame;
    aGame = new GameN(coins);
    and I have complete the code below but it's not working. maybe I'm reading it wrong or
    not understandin something. Could someone correct it? or put me on the right lines
    private int[] cGroups = new int[]
    public GameN(int group1, int group2, int group3)
    super();
    this.cGroups = {group1, group2, group3};
    }

    ShockUK wrote:
    I've changed it to
    private int[] coinGroups = new int[] {1};
    public Nim(int group1, int group2, int group3)
    super();
    int[] coinGroups = {group1, group2, group3};
    }But I still get the same error "Constructor error: Can't find constructor: Nim( [I ) in class: Nim"
    Look at the line that error is pointing at. You're trying to use a constructor that doesn't exist. This is not a problem with creating an array.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • JDEVELOPER 10G, ADF BC: Passivate static instance variables in AM?

    I understand the need to passivate/activate instance variables but what about static instance variables within an application module?
    Thanks,
    Wes

    Static variables - being class variables and not instance variables - persist without a need for passivation. Is there a particular reason or scenario why to use static variables? You have to consider that since all AM instances will share it, changing it in one AM instance - i.e. one user session - will affect all other AM instances - i.e. all other user sessions! You also have to consider the implications of multithreading when attempting to modify the static variable.

  • Calling instance variable...

    Hi,
    Just wondeirng if I defined some instance variables in a class. If I want to call the variables in another class. Is it like <class_of_variables_are_defined>.<variables> ?

    Here are the codes I have written...I am still having a little trouble though
    Variables that I have defined in two different class...
    Ride.class
    public class Ride
         private String name;
         private int ticketsRequired, numberOfRiders;
         private float heightRequirement;
         public String getName()
              return name;
         public int getTicketsRequired()
              return ticketsRequired;
         public int getNumberOfRiders()
              return numberOfRiders;
         public float getHeightRequirement()
              return heightRequirement;
    TicketBooth.class
    public class TicketBooth
         private float moneyMade;
         private int availablePasses;
         public float TICKET_PRICE = 0.5f;
         public float PASS_PRICE = 16.5f;
         public float getMoneyMade()
              return moneyMade;
         public int getAvailablePasses()
              return availablePasses;
         public TicketBooth(int initAvailablePasses)
              availablePasses = initAvailablePasses;
                         .....Now when I try to use those private instance variables in Person.class, I got bunch of errors. I know private instances can only be used within the class they defined. How should I correct the code below?
    Person.class
                         public boolean buyPass(TicketBooth booth)
              if (hasPass == true && money >=  PASS_PRICE)
                   return true;
              else
                   return false;
         public boolean allowedToRide(Ride aRide)
              if (height >= heightRequirement &&
                 (hasPass == true || ticketCount >= ticketRequired))
                   return true;
              else
                   return false;
         public void getOn(Ride aRide)
              if ((allowedToRide(aRide) == true) && (hasPass == true))
                   availablePasses -= 1;
                   numberOfRiders += 1;
              else if(ticketCount >= ticketRequired)
                   numberOfRiders += 1;
                   ticketCount -= ticketsRequired;
                         .......

  • BufferedReader bf;       is this also treated as instance variable?

    hi i m just now finished my assignment and doing documentation
    and i got a single line here
    BufferedReader bf; //instance variable
    constructor{
    bf = new BufferedReader(new InputStreamReader(System.in));
    }and now i m doing documentation suddenly i got confused whether i should
    write this as instance variable or not. should i?? or shouldn't i
    i think this is obejct,,,,,,,but..i think it is instance variable as well..coz
    it is located in the class scope..confusing.....
    or not..

    hi i m just now finished my assignment and doing
    documentation
    and i got a single line here
    BufferedReader bf; //instance variable
    constructor{
    bf = new BufferedReader(new
    w InputStreamReader(System.in));
    }and now i m doing documentation suddenly i got
    confused whether i should
    write this as instance variable or not. should i?? or
    shouldn't i
    i think this is obejct,,,,,,,but..i think it is
    instance variable as well..coz
    it is located in the class scope..confusing.....
    or not..Okay, first of all constructor {} isn't valid Java syntax, I'm assuming you just used it for brevity. Second, yes bf is an instance variable because it's not a) static (class-) variable or b) local variable.
    If you thought instance variables refer only to primitives (int, byte etc.) you're wrong. Object references can also be instance variables.
    So yes, it is both an object reference and an instance variable.
    Sincerely,
    Jussi

  • Inheritance & instance variables

    Okay, this just went against everything I thought I knew about inheritance and Java...
    So I wrote something like the code below, and when I declared
    ClassB cb = new ClassB();
    cb.variable2 was set to "". I traced it line-by-line in JBuilder's debugger, and I watched it set it to "bar" with my very own eyes, and then the tracer went to the "String variable2 = "";" line AFTER it ran the constructor. Is that supposed to happen?
    class ClassA{
         String variable1 = "";
         ClassA()
             parse();
         protected void parse()
              variable1 = "foo";
    class ClassB extends ClassA
        String variable2 = "";
        ClassB()
            super();
        protected void parse()
            super.parse();
            variable2 = "bar";

    And also: for those of you who said "never use an
    overridable method in the constructor," does this mean
    that every time you create a subclass, you must write
    a constructor that initializes all of the instance
    variables? Not exactly sure what you mean by "initializes all of the instance variables." You certainly don't need to explicitly initialize each of your object's fields in the constructor; in some cases, you won't know their values at that time.
    Doesn't this cause you to have to change all the subclasses
    individual subclasses if you ever needed to remove or change
    a superclass' instance variable (for example)?No, and this comes back to my point that a class is only responsible for the fields that it declares. If you don't try to change your superclass' fields directly, then you're not dependent on how it's implemented. Instead, you should call the appropriate superclass constructor. For example:
    public class XXX
        protected Map     _data;
        public XXX()
            _data = new HashMap();
        public XXX( Map data )
            _data = data;
    }Let's say that you now want to create class YYY, which extends XXX but uses a TreeMap instead of a HashMap. You could simply access "_data" directly; after all, it's "protected" and not "private". However, this introduces a dependency: class XXX now cannot change field "_data" without breaking class YYY. Instead, you should call the second constructor, which initializes the field from passed data:
        public YYY()
            super(new TreeMap());
        //...There are still ways that this example could break ... for example, the implementor of XXX could decide that the second constructor should copy the passed Map. There are ways to avoid this, but we won't go into those here :-)

  • Classes, and constructors and instance variables . . . oh my!

    wow, I am really struggling with the stuff we are doing in class for the last few days. I am going to post our assignment and point out specific things I don't understand. I don't understand some of the syntax and the overall logical flow of how parameters get passed back and forth, etc. I have been over our book and class examples and I am still confused.
    Here is one part of the assignment:
    "Create two instances of the MyDate class named begDate and endDate, by using the MyDate constructor after having prompted the user
    3 times for each date for values of a valid month, day, and year."
    Q: how do I create two instances using the constructor?
    (from our assignment) "Within the MyDate class:
         Include three private int variables, named month, day, and year.
         Include a constructor that sets (sets them to what?!) the values of month, day, and year."
    here is what I have:
    public class MyDate {
         private int month, day, year;
         public MyDate (int month, int day, int year){
              month = 0;
              day = 0;
              year = 0;
         }//MyDate Constructor(from our assignment) "Create two instances of the MyDate class named begDate and endDate, by using the MyDate constructor after having prompted the user 3 times for each date for values of a valid month, day, and year."
    and here is what I have in the executable class (it isn't much because I already have an error; it says I can't convert String to MyDate):
    public static void main(String[] args) {
              MyDate begDate = JOptionPane.showInputDialog("beg. month?");
         }I guess I don't know how to use the constructor correctly. Sorry, but I have tried to make this as clear as possible.

    I will give you a start:
    public static void main(String[] args) {
              MyDate begDate new MyDate(JOptionPane.showInputDialog("beg. month?"), JOptionPane.showInputDialog("beg. day?"), JOptionPane.showInputDialog("beg. year?"));
    public class MyDate {
         private int month, day, year;
         public MyDate (int month, int day, int year){
              this.month = month;
              this.day = day;
              this.year = year;
         }//MyDate Constructor
    /code]
    Haven't tested it, maybe made some type mismatches, but at leasy try this one                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Inheritance - instance variable initialization

    Hi all.
    I have a question regarding inherited instance variables.
    class Animal {
       int weight;
       int age = 10;
    class Dog extends Animal {
       String name;
    class Test {
       public static void main(String[] args) {
          new Dog();
    }This is just an arbitrary code example.
    When new Dog() is invoked, I understand that it's instance variable "name" is give the default
    type value of null before Dog's default constructor's call to super() is invoked.But Im a little perplexed about
    Animals instance variables. I assume that like Dog, Animals instance variables are given their default type values
    of 0 & 0 respectively, before Animals invocation of super(); What im unclear about is that at the point that weight and age are given their default type values, are Dog's inherited weight and age variables set to 0 aswell at that exact moment? Or are Dog's inherited weight and age variables only assigned their values after Animals constructor fully completes because initialization values are only assigned to a classes instance variables after it's call to super().
    Many thanks & best regards.

    Boeing-737 wrote:
    calvino_ind wrote:
    Boeing-737 wrote:
    newark wrote:
    why not throw in some print statements and find out?Super() or this() have to be the very first statement in a constructor..
    Also you cannot access any instance variables until after super or this.
    :-S
    Kind regardsbut if you add the "print" statement in animal constructor, you can easily see what happened to the attributes of Dog ; that s the trick to print "before" super()You can never add a print before super(). It's a rule of thumb, super() and this() must always be the first statements
    in a constructor, whether added implicitly by the compiler or not. In this case there are 2 default constructors (inserted by the compiler), each with a super() invocation. Even if i added them myself and tried to print before super(), the compiler would complain.
    Thanks for the help & regards.you didn't understand what i meant ; take a look at that:
    class Animal {
       int weight;
       int age = 10;
       public Animal() {
           Dog thisAsADog = (Dog) this;
          System.out.println(thisAsADog.name);
          System.out.println(thisAsADog.x);
    class Dog extends Animal {
       String name;
       int x = 10;
    public class Test {
       public static void main(String[] args) {
          new Dog();
    }this way you will know what really does happen

  • Parsing XML and Storing values in instance variable

    hi,
    i'm new to XML.
    here i'm trying to parse an XML and store their element data to the instance variable.
    in my main method i'm tried to print the instance variable. but it shows "" (ie it print nothing ).
    i know the reason, its becas of the the endElement() event generated and it invokes the characters() and assigns "" to the instance variable.
    my main perspective is to store the element data in instance variable.
    thanks in advance.
    praks
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    public class mysax extends DefaultHandler
         String ctelement;
         CharArrayWriter contents;
         String vname1,vrcbreg1,vaddress1,vcountry1,vtelephone1,vfax1;
         String vname,vrcbreg,vaddress,vcountry,vtelephone,vfax;
         public mysax()
              vname1 = null;
              vrcbreg1 = null;
              vaddress1 = null;
              vcountry1 = null;
              vtelephone1 = null;
              vfax1 = null;
              contents= new CharArrayWriter();
         public void doparse(String url) throws Exception
              SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    ParserAdapter pa = new ParserAdapter(sp.getParser());
    pa.setContentHandler(this);
    pa.parse(url);          
         public void startElement(String namespace,String localName,String qName,Attributes atts)
              ctelement = localName;     
         public void endElement(String uri,String localName,String qName) throws SAXException
         public void characters(char[] ch,int start, int length) throws SAXException
              try
                   if(ctelement.equals("name"))
                        vname = new String (ch,start,length);
                        System.out.println("The method "+vname1);
              }catch (Exception e)
                   System.out.println("The exception "+e);
         public static void main(String args[])
              try
              mysax ms = new mysax();
              ms.doparse(args[0]);
              System.out.println("the contents name "+ms.vname1);
              catch(Exception e)
                   System.out.println("this is exception at main" +e);
    my XML looks like
    <coyprofile_result>
    <company>     
    <name>abcTech</name>
    <rcbreg>123456789</rcbreg>
    <address>Singapore</address>
    <country>sg</country>
    <telephone>123456</telephone>
    <fax>123155</fax>
    </company>
    </coyprofile_result>

    I believe that the problem has to do with the value you assign to ctelement. You are assigning the value of localName to ctElement, however for the element: <name>...</name> the localname is empty string i.e. "", but qName equals "name". Because you are assigning empty string to ctElement, when you do the comparison in characters of ctElement to "name" it will always be false. So in startElement change it to ctElement = qName; Try it and see if it works. I have produced similar programs and it works for me.
    Hope this helps.

  • How to change value of instance variable and local variable at run time?

    As we can change value at run time using debug mode of Eclipse. I want to do this by using a standalone prgram from where I can change the value of a variable at runtime.
    Suppose I have a class, say employee like -
    class employee {
    public String name;
    employee(String name){
    this.name = name;
    public int showSalary(){
    int salary = 10000;
    return salary;
    public String showName()
    return name;
    i want to change the value of instance variable "name" and local variable "salary" from a stand alone program?
    My standalone program will not use employee class; i mean not creating any instance or extending it. This is being used by any other calss in project.
    Can someone tell me how to change these value?
    Please help
    Regards,
    Sujeet Sharma

    This is the tutorial You should interest in. According to 'name' field of the class, it's value can be change with reflection. I'm not sure if local variable ('salary') can be changed - rather not.

  • Error with instance variable and constructor of base class

    I am getting the error on the following statement "protected Point apoint" of by base class. What is causing this problem? See my code:
    package Shapes;
    public abstract class Shapes
         protected Point apoint; / ****error at this line****/
         public void move(double xdelta, double ydelta)
              apoint.x += xdelta;
              apoint.y += ydelta;
    public abstract void distance();
    public abstract void show();
    public String toString()
    return "\nThe starting point is at coordinates ("+x+","+y+")";
    package Shapes;
    public class Lines extends Shapes
    protected Point start;
    protected Point end;
         protected double x;
         protected double y;
         double delta;
         public Lines( final Point apoint, final Point bpoint)
    start.x = apoint.x;
              start.y = apoint.y;
              end.x = bpoint.x;
              end.y = bpoint.y;
    public Lines(double xstart, double ystart, double xend, double yend)
    this.xstart = xstart;
              this.ystart = ystart;
              this.xend = xend;
              this.yend = yend;
         public Lines(double x, double y)
              this.x = x;
              this.y = y;
                   public void distance(final Lines start, final Lines end)
                        delta = abs(Math.sqrt (super.x - start.x) * (super.x - end.x) +
                        (super.y - start.y) * (super.y - end.y));
                   Lines move(Point start, double delta)
                        end.x += delta;
                        end.y += delta;
                        return new Point(end);
    public Lines show()
    g.drawLine( start.x, start.y, end.x, end.y);
    public String toString()
    return super.toString()+ "\n moved distance is("
                   + start + ") : (" + end + ")"
                   +" \n to position(" + start + " ) : (" + end + ")";
    package Shapes;
    public class Rectangle extends Lines
         double delta;
    public Rectangle (Point top_lft_pt, Point bottom_rght_pt)
    super(top_lft_pt, bottom_rght_pt);
    public Rectangle(double x_top_lft, double y_top_lft, double x_bottom_rght, double y_bottom_rght)
    super(x_top_lft, y_top_lft, x_bottom_rght, y_bottom_rght);
         public Rectantgle is_it_diagonal()
              if(top_lft.x > bottom_rght.x && bottom_rght.x < top_lft.x)
                   System.out.println("Point are Not Diagonal");
                   public void distance(double delta)
                        delta = abs(Math.sqrt (top_lft.x - bottom_rght.x) * (top_lft.x - botton_rght.x) +
                        (top_lft.y - bottom_rght.y) * (top_lft.y - bottom_rght.y));
                   public Rectangle move(final Point top_lft_pt, double delta)
                        bottom_rght.x += delta;
                        bottom_rght.y += delta;
                        return new Point(bottom_rght_pt);
                   public void get_top_rght_coords()
                        Point top_rght = new Point();
                        top_rght.x = bottom_rght.x;
                        top_rght.y = top_lft.y;
                   public void get_bottom_left_coords()
                        Point bottom_lft = new Point();
                        bottom_lft.x = top_lft.x;
                        bottom_lft.y = bottom_rght.y;
         public Rectangle show()
                        g.drawLine(top_lft.x, top_lft.y, top_rght_x, top_rght_y);
                        g.drawLine(bottom_lft.x, bottom_lft.y, bottom_rght.x, bottom_rght.y);
                        g.drawLine(top_lft.x, top_lft.y, bottom_lft.x, bottom_lft.y);
                        g.drawLine(top_rght.x, top_rght.y, bottom_rght.x, bottom_rght.y);
    package Shapes;
    public class Circles extends Lines
    protected double radius;
         public double delta;
         protected Point center;
    public Circles(double x, double y, double radians)
    super(x, y);
              radius = radians;
         public Circles(Point acenter)
              center.x = acenter.x;
              center.y = acenter.y;
    public void distance()
    delta = abs(Math.sqrt(super.x - x) * (super.x - x) + (super.y - y) * (super.y -y));
         public Circles move(final Point Circles, double delta)
              return new Point(Circles);
    public void show()
    g.drawOval(Circles.x, Circles.y, radius, radius);
    package Shapes;
    import java .math .*;
    import java.util .Random ;
    public class ShapesDriver
    Shapes[] aShape = new Shapes[10];
    static double range = 101.0;
    static Random r1 = new Random();
    public static void main(String [] args)
    double[][] coords = new double[10][10];
    double[] radians = new double [10];
    Shapes anyShape = {
    new Circles(radians),
    new Lines(coords),
    new Rectangle(coords)
    Shapes aShape; /***error at this line***/
              for(int i = 1; i <= coords.length; i++)
    for(int j = 1; j <= coords.length; j++)
                                                      coords[i][j] = r1.nextDouble () * range;
                                                      radians[j] = r1.nextDouble () * range;
    aShape[i] = anyShape[r1.nextInt(aShape.length)];
    System.exit(1);

    Thanks for your help with this problem. Now I have another problem that I am having a hard time figuring out. My program is using inheritance and polymorphism. I trying to use only one version of methods in the superclass points which extends the shapes class which is the abstract superclass vs. repeating the implementation of the methods (move, show, etc.) in each of the subclasses. The error I am getting is this "declare the class abstract, or implement abstract member 'Point Shapes.move()'. As you see, move is declared abstract and of type point in the Shapes superclass and it's behavior is implemented in the subclass Points extending Shapes. The other subclasses, circle, rectangle and lines will invoke the move method from Points and return a new point object. Why I am I getting the error to declare or implement move when the implementation is in Point?
    Below is code, please help?
    import java .awt .Point ;
    public class ShapesDriver
         public static void main(String args[])
              int count = 0;
              int choice;
              Point start = null;
              Point end = null;
              System.out .println(" 1 i am here");
              start = new Point((int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
              end = new Point((int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
         System.out .println(" 2 i am here");     
         System.out.println (start);
         System.out.println(end);                         
         for(int i = 0; i <= count; i++)
              System.out .println(" 3 i am here");
              choice = (int)(4.0 * Math.random());
              System.out .println(" 4 i am here");
              System.out.println (choice);     
         switch(choice)
              case 0: //Lines
              System.out .println(" 5 i am here");
              Lines apoint = new Lines((int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                                  (int)(Math.random()* 10.0), (int)(Math.random()* 10.0));
              Point coords = new Point((int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
              new Point((int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
              break;
              case 1: //Circles
              System.out .println(" 6 i am here");
              Circles center = new Circles((double)(Math.random()* 10.0),
              (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
              (double)(Math.random()* 10.0),(double)(Math.random()* 10.0));
              Circles centerpt = new Circles((int)(Math.random()* 10.0),
              (int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
              (int)(Math.random()* 10.0), (double)(Math.random()* 10.0));
         break;
              case 2: //Rectangles
         System.out .println(" 7 i am here");
              Rectangle top_lft_pt = new Rectangle ((double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0), (double)(Math.random()* 10.0),
                             (double)(Math.random()* 10.0));
              Rectangle bottom_rgt_pt = new Rectangle ((double)(Math.random()* 10.0),
                   (double)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0), (int)(Math.random()* 10.0),
                             (int)(Math.random()* 10.0));
         break;
         default:
         System.out .println(" 9 i am here");
         System.out.println("\nInvalid shape choice =" + choice);
         System.exit(0);
         break;
         try
                   System.in.read();
                   catch(java.io.IOException ioe)
    import java .awt .Point ;
    public abstract class Shapes
         private String shape;
         public Shapes(String ashape)
              shape = new String(ashape);
         public abstract Point move();
         public double distance()
              return 0.0;
         public abstract void show();
         public String toString()
              return "\nThis shape is a" + shape;
    import java .awt .Point ;
    public class Rectangle extends Points
         protected Point top_lft;
         protected Point top_rgt;
         protected Point bottom_lft;
         protected double top_lft_x;
         protected double top_lft_y;
         protected double bottom_rgt_x;
         protected double bottom_rgt_y;
         protected Point bottom_rgt;
         protected double delta = 0;
         protected String shape = "Rectangle";
         public Rectangle(double x, double y, double top_lft_x,
                             double top_lft_y, double bottom_rgt_x,
                             double bottom_rgt_y)
              super(x, y);
              top_lft_x = top_lft_x;
              top_lft_y = top_lft_y;
              bottom_rgt_x = bottom_rgt_x;
              bottom_rgt_y = bottom_rgt_y;
         public Rectangle( double x, double y, Point bottom_rgt, Point top_lft)
              super(x, y);
              bottom_rgt_x = bottom_rgt.x;
              bottom_rgt_y = bottom_rgt.y;
              top_lft_x = top_lft.x;
              top_lft_y = top_lft.y;
         public String toString()
              return super.toString() + " coordinates top left= " + top_lft_x + "," + top_lft_y + "and bottom right" +
                   bottom_rgt_x + "," + bottom_rgt_y + ")";
         public void is_it_diagonal()
              if(top_lft_x < bottom_rgt_x && bottom_rgt_x > top_lft_x)
                   System.out.println("Points are Not Diagonal");
              public double distance()
                   distance ();
                   return delta;
              public Point move(Point top_lft)
                   move();
                   bottom_rgt_x += delta;
                   bottom_rgt_y += delta;
                   return top_lft;
              public void get_other_coords()
                   top_rgt.x = bottom_rgt.x;
              top_rgt.y = top_lft.y;
                   bottom_lft.x = top_lft.x;
                   bottom_lft.y = bottom_rgt.y;
              public void show()
                   super.show();
                   System.out.println("new coords are :");
                   System.out .println ("(" + top_lft_x + "," + top_lft_y + ")");
                   System.out .println ("top right(" + top_rgt + ")");
                   System.out .println ("(" + bottom_rgt_x + "," + bottom_rgt_y + ")");
                   System.out .println ("bottom right(" + bottom_rgt + ")");
    import java .awt .Point ;
    public class Points extends Shapes
         protected double delta = 0.0;
         protected double x;
         protected double y;
         protected String ashape = "Points";
         public Points( double x, double y)
              super("Points");
              x = x;
              y = y;
         public Points( Point start)
              super("Points");
              x = start.x;
              y = start.y;          
         public String toString()
              return super.toString() + "References coordinates(" + x + y + ")";
         public double distance(double x1, double y1 )
              return delta =(Math.sqrt(x - x1) * (x - x1) + (y - y1) *
              (y - y1));
         public Point move(Point pts)
              pts.x += delta;
              pts.y += delta;
              return pts;
         public void show()
              System.out.println("This shape is a" + ashape + "(" +
                                  "(" + x+ "," + y + ")");
    import java .awt .Point ;
    public class Lines extends Points
         double delta = 0;
         protected double x;
         protected double y;
         protected String ashape = "Lines";
         public Lines( double x1, double y1, double x, double y)
              super(x1,y1);
              x = x;
              y = y;
         public Lines(Point start, Point end)
              super(start);
              x = end.x;
              y = end.y;
         public String toString(Point end)
              return super.toString() + "line points = (" + x + "," + y +
                   "(" + end + ")";
         public double distance()
              distance ();
              return delta;
         public Point move(Point lines)
              move ();
              return lines;
         public void show()
              System.out.println("This shape is a" + ashape + "(" +
                                  "(" + x + "," + y + ")");
    import java .awt .Point ;
    public class Circles extends Points
    protected double radius;
    protected double xcenter;
    protected double ycenter;
    protected String ashape = "Circle";
         public Circles( double x, double y, double cx, double cy, double radians)
              super(x, y);
              xcenter = cx;
              ycenter = cy;
              radius = radians;
         public Circles( Point acenter, Point ref, double radians)
              super(ref);
              xcenter = acenter.x;
              ycenter = acenter.y;
              radius = radians;
         public String toString(Point ref)
              return super.toString() + " reference points (" +
                   ref + ")" +
                   "center coordinates (" + xcenter + "," + ycenter + ")";
              public double distance(Point ref)
                   return (Math.sqrt(ref.x - xcenter) * (ref.x - xcenter)
                             + (ref.y - ycenter) *
              (ref.y - ycenter));
              public Point move(Point center)
                   move();
                   return center;
              public void show()
                   System.out.println("This shape is a" + ashape + "(" +
                                  "(" + xcenter + "," + ycenter + ")");

Maybe you are looking for