Page 1 of 1

Intro to inheritance Explains the basic concept of single inheritance Rate Topic: ***** 2 Votes

#1 rumzeis  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 14
  • Joined: 15-December 10

Posted 15 December 2010 - 05:50 AM

*
POPULAR

What does it mean when one says a class inherits from another class? You can think of inheritance as an 'is a'-realtionship between two classes. Suppose we have a class Animal
public class Animal {
    private String name;

    public Animal(){
        // empty constructor
    }

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }
}


An animal may or may not have a name, we can assign and retireve the name by its setter and getter methods.

Now, let's suppose we are interested in dogs. A dog may, or may not, have a name, but for shure a dog is of a specific breed (or not-so-specific crossbreed..). For the class Dog this means it shares the features of Animal plus some new features (its breed) - it extends the features of Animal. So Dog inherits from Animal, or in real-world language a Dog is an Animal. The class Dog will then look like the following
public class Dog extends Animal{
    private String breed;

    public Dog(String breed){
        this.breed = breed;
    }

    public String getBreed(){
        return breed;
    }
}


The keyword extends indicates the 'is a'-relationship between Animal and Dog. Dog has all the attributes and methods of Animal plus its own attributes and methods. We can verify this
    public static void main(String[] args) {
        Dog dog1 = new Dog("Griffon");
        dog1.setName("Barky");
        System.out.println(dog1.getName()+" is a "+dog1.getBreed());
    }


and the we get
Barky is a Griffon


So, the sublass (Dog) gets access to the features of the Superclass (Animal).

Note: A Subclasses can not directly access the private attributes of its Superclass, this will throw a java.lang.RuntimeException. To grant acces to the attributes of the superclass you can:
  • make the attributes public (not so good..)
  • make the attributes private and provide public or protected setters and getters
  • make the attributes protected (visible in the whole package)


Let's take this a step further, say we have a vicious dog and there is a fair chance that it will bite the postman. To implement the class ViciousDog we can inherit from Dog (ViciousDog is a Dog) and extend it with a variable that holds the chance that the dog will bite.

Note: The following code is wrong and will not compile! I just want do demonstrate something.
public class ViciousDog extends Dog{
    private int bites;

    public ViciousDog(int bites){
        this.bites = bites;
    }

    public int getBites(){
        return bites;
    }

    public void setBites(int bites){
        this.bites = bites;
    }
}


try it out
    public static void main(String[] args) {
        ViciousDog vdog = new ViciousDog(50);
    }


and we get a java.lang.RuntimeException.
End of wrong code.

Why's that?
When you instantiate a subclass it makes a call to the constructor of its superclass. All classes have an (empty) default constructor if not specified otherwise, so we could have omited the (empty) constructor in Animal. The call to the constructor of Animal in Dog happens automaically without the need of any additional code.
The constructor of Dog, however, awaits a parameter, the dogs breed. How do we call that constructor from ViciousDog? The solution is provided by the keyword super, which delegates parameters to the constructor of the superclass. The correct code for ViciousDog is then
public class ViciousDog extends Dog{
    private int bites;

    public ViciousDog(String breed, int bites){
        super(breed);
        this.bites = bites;
    }

    public int getBites(){
        return bites;
    }

    public void setBites(int bites){
        this.bites = bites;
    }
}


Try it out again
    public static void main(String[] args) {
        ViciousDog vdog = new ViciousDog("Griffon",50);
        vdog.setName("Barky");
        System.out.println(vdog.getName()+" is a "+vdog.getBreed()+" and bites with a chance of "
                                         +vdog.getBites()+" percent.");
    }


the output is
Barky is a Griffon and bites with a chance of 50 percent.


We see that ViciousDog gets acces to the attributes and methods of Dog and the attributes and methods that Dog inheritited from Animal. Inheritance offers us a geat way of refactoring code, when designing a new class and you already have a class that has some of the desired features of you new class, you can simply inherit from that class and add all the extra functionality you need, without the need to design everything from scratch.

I hope this is useful to some of you new to Java or OOP.
Have fun, experiment and share your findings!

This post has been edited by rumzeis: 15 December 2010 - 12:52 PM


Is This A Good Question/Topic? 11
  • +

Replies To: Intro to inheritance

#2 Guest_queenpictoria*


Reputation:

Posted 12 February 2011 - 10:42 AM

I do not view this as an Intro to Inheritance.
It is far too complicated and assumes I know things I do not yet understand.

I also don't appreciate the sense of humor regarding dog bites, etc.
It's distracting and ugly. Sorry if you do not like my feedback.
If you want me to go elsewhere, just say so.
Thanks.

This post has been edited by macosxnerd101: 12 February 2011 - 08:19 PM
Reason for edit:: Removed the quote. No need to quote the person above you, especially when the quote is really long.

Was This Post Helpful? -8

#3 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10786
  • View blog
  • Posts: 40,163
  • Joined: 27-December 08

Posted 12 February 2011 - 08:18 PM

Have you covered class design or any OOP yet? You should have a basic understanding of class design and OOP at least before covering inheritance.
Was This Post Helpful? 0
  • +
  • -

#4 Rxanadu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 30-March 11

Posted 20 May 2011 - 09:57 AM

Hello, I was wondering how I could get this class to display the information within the displayStatistics method without resorting to making every method static.
package sphere_tutorials;

public class Sphere {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Hello");
	}
	
	private double theRadius;
	
	public Sphere(){
		setRadius(1.0);
	}
	
	public Sphere (double initialRadius){
		setRadius(initialRadius);
	}
	
	public boolean equals (Object rhs){
		return ((rhs instanceof Sphere) &&
				(theRadius == ((Sphere)rhs).theRadius));
	}
	
	public void setRadius(double newRadius){
		if (newRadius >= 0.0){
			theRadius = newRadius;
		}
	}
	
	public double radius(){
		return theRadius;
	}
	
	public double diameter(){
		return 2.0 * theRadius;
	}
	
	public double circumference(){
		return Math.PI * diameter();
	}
	
	public double area(){
		return 4.0 * Math.PI * theRadius * theRadius;
	}
	
	public double volume(){
		return (4.0 * Math.PI * Math.pow(theRadius, 3.0)) / 3.0;
	}
	
	public void displayStatistics(){
		System.out.println("\nRadius = " + radius() +
				"\nDiameter =  " + diameter() + 
				"\nCircumference = " + circumference() + 
				"\nArea = " + area() +
				"\nVolume = " + volume());
	}

}



I know, I know. It only displays "Hello" when you run it, and yes, I know that if you set every method to static then call the displayStatistics method in the main method, it will work. I was wondering if that was the only way to get the program to display that information short of ripping everything out of the displayStatistics method and placing it within the main.

Thank you for taking the time out to read this.
Was This Post Helpful? 0
  • +
  • -

#5 Niha  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 42
  • Joined: 20-April 07

Posted 27 June 2011 - 05:12 AM

View Postqueenpictoria, on 12 February 2011 - 10:42 AM, said:

I do not view this as an Intro to Inheritance.
It is far too complicated and assumes I know things I do not yet understand.

I also don't appreciate the sense of humor regarding dog bites, etc.
It's distracting and ugly. Sorry if you do not like my feedback.
If you want me to go elsewhere, just say so.
Thanks.



It says intro to inheritance not intro to Java. And I don't think the author was trying to be humorous either; all in all, I say this tutorial is SUPERB because I 've understood inheritance now. Thanks a lot, rumzeis!! (especially about the super part; I'd never understood that before)
Was This Post Helpful? 1
  • +
  • -

#6 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Posted 04 July 2011 - 08:18 PM

Thanks for the good post. I am vaguely aware of constructors of superclass being called when subclasses call their own constructors. I guess we have touched upon the topic( for like 10 minutes, no kidding) now it's all clear to me. Thanks. :)
Was This Post Helpful? 0
  • +
  • -

#7 MasterZeddicus  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 39
  • Joined: 30-January 12

Posted 29 March 2012 - 05:04 AM

Great tutorial! Answered a lot of my questions regarding when exactly super is needed, and also helped me remove a lot of redundant code. The original guy who replied evidently was just looking for a copy paste template he could use and has no idea what he's doing with Java. =/

5 stars! :D
Was This Post Helpful? 0
  • +
  • -

#8 Xente  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 36
  • Joined: 31-January 12

Posted 31 March 2012 - 11:25 AM

Cool tutorial, it simplifies inheritance to a great degree.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1