Classes & Objects

From Java Programming II
Jump to: navigation, search

Classes and Objects in Java

Learning Outcomes

  • How to declare a class and use it to create an object.
  • How to implement a class’s behaviors as methods.
  • How to implement a class’s attributes as instance variables and properties.
  • How to call an object’s methods to make them perform their tasks.
  • What instance variables of a class and local variables of a method are.
  • How to use a constructor to initialize an object’s data.
  • Encapsulation and data hiding (using private access specifier and data validation).
  • To use keyword this.
  • To use static variables and methods.
  • To import static members of a class.

Lecture notes

  • A class is an entity that contains attributes and methods. Attributes or instance variables represent a characteristic of the entity. The methods represent operations on these attributes.
  • The general declaration and creation of an object in Java is in the form
 ClassName ObjectName = new ClassName(); 

Example:

 Student student = new Student(); 
  • A constructor: it is a method that:
    • does not have any return type
    • has the same name of the class
    • must be public
  • Java defines for you a default constructor that initialized all your attributes to null or default values. When you define a constructor with parameters, the default constructor will no longer be available. It is overrideen. You must then define your own default constructor.
  • Access specifier: determines how to access an attribute or a method. Access specifiers are public by default or private
  • A good programming practice is to make all attributes as private and restrict their access from external classes. This called data hiding or encapsulation, because data is hidden from external classes.
  • Why data hiding is a good programming practice?
    • this is needed to perform data validation , i.e. ,make sure that values assigned to attributes are valid
    • does not allow external program to put non valid values.
  • How to access (read/write) the private attributes?
    • use get methods to read an attribute value
    • use the set methods to modify the value of the attribute
  • this is a keyword in Java that refers to the object of the same class where it is called.
  • thiskeyword can be used to call the constructor of the class.
  • Constructor overloading: means having several constructors inside the same class.
  • copy constructor: it is a constructor that copies an object into another one, meaning a constructor with an object of the same class as parameter.
  • toString() method is a special method that provides a String representation for any object in Java. By default, it returns a reference to the object

but, you can override (changing its definition) it to return another string representation of the object.

  • static keyword: creates a shared attribute or method for all created objects, i.e. class-wide attribute or method.
  • The keyword final is used to create constant values, .i.e cannot be changed.
  • Composition is the has-arelationship between two classes. We say that a class is composed of an object of another class or a class has-a object of another class. For example, the class Employee has an object of the class Date.


Codes

Without object-oriented design

StudentProgram code

public class StudentProgram {
   
   public static void main(String []args){
       String st1LastName="Ali";
       String st1ID="S123456";
       
       String st2FirstName="Mohsen";
       String st2LastName="Mounir";
       String st2ID="S543216";
       
       System.out.printf("Student 1: %s %s (%s)\n", st2FirstName, 
               st1LastName, st1ID);
       System.out.printf("Student 2: %s %s (%s)\n", st2FirstName, 
               st2LastName, st2ID);
       
       
       
   }
   
}


Using object-oriented design

Student class

public class Student {
   
   //attributes of the class students
   private String firstName;
   private String lastName;
   private String id;
   private String mobilePhone;
   private static int count;
   
   private final int max_age = 40;
   
   public Student(){
       count++;
   }
   
   public Student (String fn, String ln, String ID, String mp){
      /*firstName = fn;
      lastName = ln;
      id = ID;*/
       
      this.setFirstName(fn);
      setLastName(ln);
      setId(ID);
      /*if (mp.length()==10)
      mobilePhone=mp;*/
      setMobilePhone(mp);
      count++;
   }
   
   public Student (String fn, String ln){

      this.setFirstName(fn);
      setLastName(ln);
      count++;
   }
   
   public static int getCount(){
       return count;
   }
   
   public String getMobilePhone(){
       return mobilePhone;
   }
   
   public void setMobilePhone(String mp){
       if (mp.length()==10)
       mobilePhone = mp;
   }
   
   public String getFirstName(){
       return firstName;
   }
   public String getLastName(){
       return lastName;
   }
   public String getId(){
       return id;
   }
   
   public void setFirstName(String fn){
       if (fn.length()>2)
       firstName=fn;
   }
   
   public void setLastName(String ln){
       if (ln.length()>2)
       this.lastName=ln;
   }
   
   public void setId(String id){
       this.id = id;
   }
   
   
   //methods
   public void displayStudentInfo(){
       System.out.printf("%s %s (%s) {%s}\n", firstName, 
               lastName, id, mobilePhone);  
   }
   
   public void displayName(){
       System.out.printf("%s %s \n", firstName, 
               lastName);  
   }
   
   public String toString(){
       return String.format("%s %s (%s)", firstName, lastName, 
               this.mobilePhone);
   }
       
}


public class StudentTest {
   public static void main(String []args){
       Student st1 = new Student("Mohamed", "Ali", "S123456", "0504");
       System.out.println(Student.getCount());
       Student st2 = new Student("Mohsen", "Mounir","S999999",  "0504123459");
       System.out.println(Student.getCount());
       Student st3 = new Student("Karim", "Ahmed");
       System.out.println(Student.getCount());
       
       st1.displayStudentInfo();
       st2.displayStudentInfo();
       
      
      
       st3.displayStudentInfo();
       //st1.mobilePhone="0574145741";
       System.out.println("mobile phone before the change: "+ st1.getMobilePhone());
       st1.setMobilePhone("0574149999");
       System.out.println("mobile phone after the change: "+ st1.getMobilePhone());
       //st2.firstName = "Mohsen";
       //st2.lastName = "Mounir";
       //st2.id = "S999999";
       
       
       System.out.println(st1);
       System.out.println(st2);
       System.out.println(st3);

               
   }
    
}

Videos

Introduction to Classes


Data Hiding and Encapsulation


Static Members and Constructor Overloading

Composition (Has-a relationship)

Solution of Quiz 01 Spring 2018: Distance Sensor

Solution of Practice Quiz Fall 2015: Temperature

Solution of Practice Quiz Fall 2016: Geolocation class

Solution of Practice Quiz Fall 2015 by Student Kamal Ghassan