Pages

Tuesday, May 6, 2025

Getters and Setters in OOPs

 class Student {

    private:

    //Properties


    string name;

    float cgpa;


    public:

    

    //Setters

    void setName(string nameVal) {  // remember to include #include <string> as well

        name = nameVal;

    }

    

    void setCgpa(float cgpaVal) {

        cgpa = cgpaVal;

    }

    

    //Getters

    string getName() {

        return name;

    }

    

    float getCgpa() {

        return cgpa;

    }

    


    //Methods


    void getPercentage() {


        cout << (cgpa*10) << endl;


    }


};




class User{


    int id;


    string username;


    string password;


    string bio; 


    


    void deactivate() {


        cout << "deactivating account\n";


    }


    


    void editBio(string newBio) {


        bio = newBio;


    }


};




int main() {


    Student s1; // objects

    s1.setName("raju");

    s1.setCgpa(9.0);

   

    cout << s1.getName() << endl;

    cout << s1.getCgpa() << endl;

 

}



MISTAKES:- 

    1. I put s1.setName = "raju"; which is WRONG!

        correct way:- s1.setName("raju");

    2. i did same for s1.setCgpa as well, learnt mistake ! 

No comments:

Post a Comment

Multi-dimensional ArrayList in Java

  // import java.util.ArrayList; import java.util. * ; // import java.util.Collections; public class Classroom {     public static voi...