Java Help

Discussion in 'School Work Help' started by Woody, Sep 28, 2010.

  1. yea, if you haven't learned inheritance, it would be normal for you to be confused.

    So you already know what a class is.. a class is pretty much a blueprint from which an object is created.. such as the Rectangle class. But a class doesn't necessarily need to restrict itself to what you make that class to be. The class can extend another class.

    Before I dive into class extension, let me just explain the concept of inheritance. Say you have a class called Parent. Parent has so and so attributes, and so and so methods.

    The Parent has a child, and this child inherits everything of the parent, but can add more. If the Parent is of a specific ethnicity, then the child is of the same ethnicity for example. The child inherits everything that belongs to the parent, and can add more to itself. make sure you don't do the opposite, because a parent cannot inherit from a child, can he/she?

    In terms of programming, it's not much different. Basically, you can create a new class, based on existing classes. This way, you don't have to rewrite classes that already exists, and all you need to do is add more to it.

    So say you want to write a class called Cat. Cat is a type of animal, but you don't want to rewrite animal, because it already exists. then what you can do is write the Cat class, and extend the Animal class.

    Code:
    public class Cat extends Animal {
    ...
    }
    
    This allows the Cat to inherit everything that belongs to an Animal... i.e. 4 paws, a mouth, eyes, ears.. tail... etc. You can then only need to define things that are unique to cat... like whiskers... meowing..... etc.

    However the problem with extension is, you can ONLY extend one class. so for example, if you want to extend Animal, AND another class like Pet.... you can't.....

    That's where Class implementation comes in. When you implement another class, you can implement more than one class... take a look at below:

    Code:
    public class Cat extends Animal implements Pet {
    ...
    }
    
    The nice thing with implementation instead of extension is that you can inherit from more than one class.. problem? unlike extension, you actually have to rewrite all the methods that belong to the implemented interface.. (implemented class is called an interface)....

    So for example, all of the methods that are defined in Pet class needs to be rewritten in your Cat class... implementation basically tells you what you need to add to your Cat class to make it perform like a Pet.

    This is wear the @override comes in. When you implement an interface, all the methods that the interface requires you to rewrite in your Cat class, needs to be overridden.. so if your Pet class has the method "eatsFromBowl()", your Cat class needs to have a method "eatsFromBowl()" in it as well, but with "@Override" at the top:

    Code:
    @Override
    public void eatsFromBowl() {
    ...
    }
    
    that's basically the jits of it.... other than that, youll have to wait until your prof covers it.... im still trying to understand why your prof tells you to do things that he hasn't covered yet.............
     
  2. Woody

    Woody Well-Known Member

    213
    41
    0

    Thank you. I get the beginning part, but not the Interface part. I'll leave this out for now. I'll come back to this someday.

    I study really hard for this because I'm slow. Thanks for helping me.
    :biggthumpup:
     
    #22 Woody, Oct 13, 2010
    Last edited: Oct 13, 2010
  3. hongkongboy

    hongkongboy Well-Known Member

    707
    68
    0
    yeh it is the standard concept for companies around the business market but i dont think its a 100% gaurantee and a succesful rate

    the concept is just a guidelines, im sure companies take risk skip steps n have become successful others might have follow the concept but also failed.

    but yeh that my opinion i love going against the world. dan can i ask what you do for a livining it seems you have a strong opinion of many interesting things
     
  4. I am a university student
     
  5. hongkongboy

    hongkongboy Well-Known Member

    707
    68
    0
    your defo doing a programming degree arent yah?
     
  6. computer science major, communications culture information technology major

    ibm internship for 16 months
     
  7. Woody

    Woody Well-Known Member

    213
    41
    0
    This is my practice lab test.

    I have the solutions for the test.
    For the constructor, the part when it says, ".....and now as the given issue date."

    I went over to the API of the Date class to see what I can find.
    The solutions end up using the calender. I looked up the API of calender, and it makes sense to use it because it initialize the attribute with the current date and time. This isn't that obvious. I could have used the """public Date()""" method (but that's confusing). Any tips?

    Code:
    public Transfer(String station)
    	{
    		this.station = station;
    		this.calendar = Calendar.getInstance();
    	}
    
     

    Attached Files:

  8. there is no right or wrong in using date or calendar, because they both solve your problem... however, there is a best practice... several methods that are associated with Date are depreciated, which means they are outdated and no longer used. Calendar offers more methods and more features, which is why people use Calendar over Date.

    see these articles for more info:

    http://stackoverflow.com/questions/1404210/java-date-vs-calendar
    http://lavnish.blogspot.com/2007/12/java-calendar-vs-date.html
     
  9. Woody

    Woody Well-Known Member

    213
    41
    0
    What is difference between:

    Code:
     public String getName()
        {
            return name;
        }
    
    and

    Code:
     public String getName()
        {
            return this.name;
        }
    
    
    The solutions used 'return name'.
    Thanks. -flow
     
  10. normally it doesn't matter, but when your code deals with scopes, it matters a lot.

    given:

    Code:
    class A {
         int i = 99;
    
         int someMethod1(int i) {
              i = i;
              return i;
         }
         int someMethod2(int i) {
              this.i = i;
              return this.i;
         }
         int someMethod2(int i) {
              i = i;
              return this.i;
         }
    
    
    and if i run:

    Code:
    System.out.println(someMethod1(10);
    System.out.println(someMethod2(20);
    System.out.println(someMethod3(30);
    
    tell me what each line will print?

    hint: first method has a local scope, second method has a global scope, and what does the third method return?

    i'm expecting that you reply to my response... i don't particularly appreciate that you ask, and then you take off =\
     
  11. Woody

    Woody Well-Known Member

    213
    41
    0
    10
    20
    (There's no someMethod3, lol. Assume the last method is someMethod3)
    20


    Hope it's correct.
     
  12. Flower

    Flower Well-Known Member

    128
    16
    0

    This is right.-lol
     
  13. Woody

    Woody Well-Known Member

    213
    41
    0
    [HIDE]Methods inherited from class pex06.Person
    getAge, getName, getNumberOfPersons, setName


    a constructor:

    Adult

    public Adult(String name,
    int age,
    String number)

    Constructs an adult with the given name, age, driver's licence number.

    Parameters:
    name - The name of the adult.
    age - The age of the adult.
    number - The driver's licence number of the adult.
    Precondition:
    age >= MIN_AGE
    [/HIDE]


    [HIDE]
    Code:
    
    I wrote this:
           public Adult(String name, int age, String number)
           {
            if(this.setAge(age))
            {
                super(name, age);
                this.licenceNumber = number;
               
            }
           
        }
    
    
        public boolean setAge(int age)throws IllegalArgumentException
        {
            if(age >= Adult.MIN_AGE)
            {
                return true;
            }
            else
            {
                throw new IllegalArgumentException("age needs to be greater than or equal to MIN_AGE.");
            }
           
        }
    
    
    [/HIDE]



    Code:
    
    I'm getting an error:
    it says that super(...) must be the first statement in a constructor.
    
    	public Adult()
    	{
    		Random random = new Random();
    		if(random.nextBoolean())
    		{
    			super(Adult.MIN_AGE, "John Doe");
    
    		}
    		else
    		{
    			super(Adult.MIN_AGE, "Jane Doe");
    		}
    	}
     
    #33 Woody, Oct 29, 2010
    Last edited: Oct 29, 2010
  14. Woody

    Woody Well-Known Member

    213
    41
    0
    Sorry about the previous code. I figured out how to do it. If you are feeling confused about that. Here are the solutions that I've made:

    [HIDE]
    Code:
    [SIZE="2"]/**
     *
     */
    package pex06;
    import java.util.Random;
    
    import pex06.Person;
    
    public class Adult extends Person
    {
        public static final int MIN_AGE = 18;
        private String licenceNumber;
    
        public Adult()
        {
            Random random = new Random();
            if(random.nextBoolean())
            {
                super.setName("John Doe");
                super.setAge(Adult.MIN_AGE);
            }
            else
            {
                super.setName("John Doe");
                super.setAge(Adult.MIN_AGE);
            }
        }
    
        /**
         * Constructs an adult with the given name, age, driver's licence number.
         * @param name The name of the adult.
         * @param age The age of the adult.
         * @param number The driver's licence number of the adult.
         */
        public Adult(String name, int age, String number)
        {
            super(name, age);
            this.licenceNumber = number;
        }
    
        /**
         * Constructs an adult with the same name, age and driver's licence number as the given adult.
         * @param adult - An adult.
         * @pre. adult != null
         */
        public Adult(Adult adult)
        {
            super(adult.getName(), adult.getAge());
            if(adult != null)
            {
                this.licenceNumber = adult.licenceNumber;
            }
        }
    
        /**
         * Returns the driver's licence number of this adult.
         * If this adult does not have a driver's licence, then null is returned.
         * @return The driver's licence number of this adult.
         */
        public String getNumber()
        {
            return this.licenceNumber;
        }
    
    
        /**
         * Sets the age of this adult to the given age if the given age is greater than or equal to MIN_AGE.
         * @param age - The new age of this adult.
         * @return true if age is equal to or less than MIN_AGE, otherwise throw IllegalArgumentException
         * @throws IllegalArgumentException - if age < MIN_AGE.
         */
    
        public boolean setAge(int age)throws IllegalArgumentException
        {
            if(age < Adult.MIN_AGE)
            {
                throw new IllegalArgumentException("age needs to be greater than or equal to MIN_AGE.");           
            }
            else
            {
                super.setAge(age);
                return true;
            }
        }
    
    
        /**
         * Tests for equality of this adult and the given other object.
         * Two adults are equal if they have the same name, the same age and the same driver's licence number.
         * If both names are null, then they are considered the same.
         * If both numbers are null, then they are considered the same as well.
         *
         *@param other - Another object.
         */
        public boolean equals(Object other)
        {
            boolean equal;
            if(other != null && this.getClass() == other.getClass())
            {
                Adult anotherObject = (Adult) other;
                equal = super.equals(anotherObject) && this.licenceNumber.equals(anotherObject.licenceNumber);
            }
            else{
                equal = false;
            }
            return equal;
    
        }
    
        /**
         * Returns a string representation of this adult.
         * This string representation consists of the name of this adult followed by the string " is " followed by the age of this adult followed by the string " year(s) old", followed, on the next line, either by the string "has a driver's licence with number " followed by the driver's licence number of this adult, or by the string "has no driver's licence".
         */
        public String toString()
        {
            if(this.licenceNumber != null)
            {
                return super.getName() + " is " + super.getAge() + " year(s) old" + "\n" +  "has a driver's licence with number " + this.licenceNumber;
            }
            else
            {
                return super.getName() + " is " + super.getAge() + " year(s) old" + "\n" +  "has no driver's licence";
            }
        }
    } [/SIZE]
    
    [/HIDE]