Inheritance Example in Java

By: Watson Emailed: 1728 times Printed: 2329 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Here is the sample b for a possible implementation of a Bicycle class and demonstrates the concept of Inheritance in JAVA.

public class Bicycle {
	
    // the Bicycle class has three fields
    public int cadence;
    public int gear;
    public int speed;
	
    // the Bicycle class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }
	
    // the Bicycle class has four methods
    public void setCadence(int newValue) {
        cadence = newValue;
    }
	
    public void setGear(int newValue) {
        gear = newValue;
    }
	
    public void applyBrake(int decrement) {
        speed -= decrement;
    }
	
    public void speedUp(int increment) {
        speed += increment;
    }
	
}

A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:

public class MountainBike extends Bicycle {
	
    // the MountainBike subclass adds one field
    public int seatHeight;

    // the MountainBike subclass has one constructor
    public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;
    }	
	
    // the MountainBike subclass adds one method
    public void setHeight(int newValue) {
        seatHeight = newValue;
    }	

}

MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. Except for the constructor, it is as if you had written a new MountainBike class entirely from scratch, with four fields and five methods. However, you didn't have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(16)


1. View Comment

where's your main sir?

View Tutorial          By: armor at 2010-12-08 01:00:45
2. View Comment

where is the main class dear.................

View Tutorial          By: akhand at 2011-03-01 23:58:05
3. View Comment

we know how declare constructor and methods but we need how to call the constructors.

View Tutorial          By: sreekanth at 2011-05-04 02:49:29
4. View Comment

You don't have to call the constructors. When you create an instance of that class, the constructors will be called automatically by the jvm

View Tutorial          By: Watson at 2011-05-04 10:44:23
5. View Comment

constructors are not to be called. when you make an object of the class bicycle, you simply pass your values for it. the constructor in bicycle takes care of initialising its own and its super's variable. :)

View Tutorial          By: niyati at 2011-05-28 07:57:52
6. View Comment

if the "extend" word is not present does that code still be an inheritance?

View Tutorial          By: detteskii at 2011-06-27 09:12:23
7. View Comment

hey guys the talk waz about main
hey man where is ur main?


View Tutorial          By: shivam at 2011-07-09 11:45:54
8. View Comment

ya its correct but tell me where is main method???is it possible to rum without maim??

View Tutorial          By: kashiNATH MOKASHI at 2011-08-20 05:33:19
9. View Comment

You only need 1 main method per application, not 1 per class. There is no requirement to have a main method in either of these classes.

View Tutorial          By: Michael at 2011-09-02 02:37:51
10. View Comment

I executed this program with the help of below code

public class inheritanceBicycle {

public static void main(String args[]) {

//create the objects of Bicycle & mountainBike
Bicycle B = new Bicycle(10,20,30);
mountainBike m = new mountainBike(1,2,300,4);
// for Bicycle
System.out.println("value of speed of bicycle " + B.speed);
B.speedUp(7);
System.out.println("value of speed after increase " + B.speed);
System.out.println("value of speed of mountainbike " + m.speed);
m.speedUp(7);
System.out.println("value of speed after increase " + m.speed);

}

}


View Tutorial          By: leela at 2011-09-08 12:16:24
11. View Comment

Your code will not execute using above main method it will give following 2 errors while compiling

inheritanceBicycl.java: cannot find symbol
symbol : class mountainBike
location: class inheritanceBicycle
mountainBike m = new mountainBike(1,2,300,4);
^
inheritanceBicycl.java: cannot find symbol
symbol : class mountainBike
location: class inheritanceBicycle
mountainBike m = new mountainBike(1,2,300,4);
^


View Tutorial          By: Gajanan Patil at 2012-05-09 04:42:29
12. View Comment

main is not needed for a simple program...
constructor gets invoked when the program runs... we can set parameters for constructors....


if anything is wrong pls forgive me....


View Tutorial          By: manoj at 2012-05-29 17:46:08
13. View Comment

The program will work only need to change
mountainBike m = new mountainBike(1,2,300,4);
Here M should be capital & remove public from both the above
classes


View Tutorial          By: LEENA NARULA at 2012-06-15 06:45:06
14. View Comment

i cant understand the concept.please mail me the full code which is ready to execute...

View Tutorial          By: nirmal at 2012-12-17 06:53:14
15. View Comment

I lit'l modified the above program for main class, Its executing for me:

public class InheritanceBicycle {

public static void main(String args[]) {

//create the objects of Bicycle parent class
Bicycle B = new Bicycle(10, 20, 30);
//create the objects of Bicycle child class mountainBike
MountainBike m = new MountainBike(1, 2, 300, 4);
// for Bicycle
System.out.println("value of speed of bicycle " + B.speed);
B.speedUp(7);
System.out.println("value of speed after increase " + B.speed);
System.out.println("value of speed of mountainbike " + m.speed);
m.speedUp(7);
System.out.println("value of speed after increase " + m.speed);

}
}


View Tutorial          By: Adil khan at 2013-02-12 06:37:17
16. View Comment

thankyou

View Tutorial          By: gomu at 2014-07-08 09:19:13

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Watson
Inheritance Example in Java
Calling a Stored Procedure from JDBC in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
The Basic Structure of a Simple Java program
XML and Java - Parsing XML using Java Tutorial
What is Java?
Method Overloading (function overloading) in Java
Method Overriding in Java
How to use ArrayList in Java
FileReader and FileWriter example program in Java
Vector example in Java
Simple Port Scanner application using Java
append() in Java
Read from a COM port using Java program
Calendar - sample program in Java
Count number of vowels, consonants and digits in a String in Java
indexOf( ) and lastIndexOf( ) in Java
Most Emailed Articles (in Java)
Vector in Java - Sample Program
Configuring a DataSource in Tomcat
Applet Notinited : Applet xxxxxxxxxxxx notinited
Use of 'finally' in Java
Basics of Exception Handling in Java
Tomcat and httpd configured in port 8080 and 80
Calculate average sale of the week in Java
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
LinkedList in Java
Taking the size of an Array at runtime & generate random numbers to populate the Array
Getting Started with Java
Creating Users and Passwords with Tomcat using tomcat-users.xml
What is JasperReports?