Class Concept in Java Programming : Explained with Real Life Example
Consider Person as a class. Now we can have some properties associated with this class Person such as
Attributes of Person :
- Name of Person
- Gender
- Skin Color
- Hair Color etc.
Now these are the general properties which forms template of the class Person,and above properties of the are called as Attributes of the Class.
Now Person class may have some core functionality such as –
- Talking
- Walking
- Eating
Thus in short Class have –
- Class name
- Properties or Attributes
- Common Functions
Now ,we are going to create objects of the class , i.e actual instance of the class. Let us say that we have created objects such as “Ram”,”Sam”. Both will have same attributes and functionality but have different attribute value.
Now this is just a template , called as “Class” , and Object is instance of the class.
Summary : Class Concept in Java Programming (Quick Look Class)
The introduction to object-oriented concepts in the lesson titled Object-oriented Programming Concepts used a bicycle class as an example, with racing bikes, mountain bikes, and tandem bikes as subclasses. Here is sample code for a possible implementation of a Bicycle
class, to give you an overview of a class declaration. Subsequent sections of this lesson will back up and explain class declarations step by step. For the moment, don't concern yourself with the details.
Syntax of Class :
- A Class is a blueprint or a template to create objects of identical type.
- A Class is core concept of Object Oriented Programming Language.
A class declaration for apublic 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; } }MountainBike
class that is a subclass ofBicycle
might look like this:
public class MountainBike extends Bicycle { // the MountainBike subclass has // 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 has // one method public void setHeight(int newValue) { seatHeight = newValue; } }MountainBike
inherits all the fields and methods ofBicycle
and adds the fieldseatHeight
and a method to set it (mountain bikes have seats that can be moved up and down as the terrain demands).
Great post. Enjoyed it. java training in chennai
ReplyDelete