Object Oriented Programming –
It is a methodology to design a Program and also provides below below concepts to simplify the software development and their maintenance.
Before moving to actual OOP concepts, we need to understand few terms, so let’s discuss one by one
For detailed information of this blog, watch this video –
Class
A class is an outline or a blueprint from which objects are created.
Example – Class Student
Object
Object is actual entity which have state(variables) and behavior(methods).
Example –
State – RollNo, Name etc…
Behavior – DispRoll(), SetRoll(), etc…
Member variables
- Local variable – if declared inside a method
- Instance variable – Inside class, but outside method (accessed by object)
- Class/static variable – Inside class, but outside method (accessed by ClassName)
Methods / Functions
Keyword “new” – to create an object
Constructor – method name same as class name
- Default
- Parameterized
Keyword “this” – if local and instance variable is same name
Code samples
public class Student { int RollNo; //instance variable String Name; //instance variable //static String SchoolName = "ABC SCHOOL"; //class variable String SchoolName; public void InsertData(int roll, String name) { //roll and name are my local variables RollNo = roll; Name = name; } Student(){ //default constructor SchoolName = "ABC SCHOOL"; } public void DispDetails() { System.out.println("Name - " + Name + " | " + "Roll No - " + RollNo); } public static void main(String[] args) { Student s1 = new Student(); s1.InsertData(123, "Ram"); s1.DispDetails(); System.out.println(s1.SchoolName); //System.out.println(SchoolName); Student s2 = new Student(); //s2.InsertData(roll, name); } }
Parameterised constructor
public class StudentParaConst { int RollNo; //instance variable String Name; //instance variable static String SchoolName = "ABC SCHOOL"; //class variable /*StudentParaConst(int roll, String name){ //parameterized constructor RollNo = roll; Name = name; } */ StudentParaConst(int RollNo, String Name){ //parameterized constructor this.RollNo = RollNo; this.Name = Name; } public void DispDetails() { System.out.println("Name - " + Name + " | " + "Roll No - " + RollNo); } public static void main(String[] args) { StudentParaConst s1 = new StudentParaConst(123, "John"); s1.DispDetails(); System.out.println(SchoolName); } }
Method with return
public class Person { int age; int AgeLimit = 60; void CurrentAge(int age) { this.age = age; System.out.println("Current age is = "+ age); } int RetPeriodLeft() { return AgeLimit - age; } public static void main(String[] args) { Person p1 = new Person(); p1.CurrentAge(45); System.out.println("Ret age left " + p1.RetPeriodLeft() + " years more"); } }