Objects and Classes

Chapter 9

Code Repo

OO Programming Concepts

  • Object-oriented programming (OOP) involves programming using objects.
  • An object represents an entity in the real world that can be distinctly identified.
  • For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.
  • An object has a unique identity, state, and behaviors.
  • The state of an object consists of a set of data fields (also known as properties) with their current values.
  • The behavior of an object is defined by a set of methods.

Class/object/Function/Method

What is a Class?

  • A CLASS is a "blueprint" from which we create OBJECTS. It is a blueprint for an object
  • Class represents state and behaviors of that object
  • OBJECTS have a “state” of existence defined by ATTRIBUTES.
  • The ATTRIBUTES of an OBJECT are defined by the VARIABLES in the Object’s CLASS.
  • OBJECTS have “behaviors” that are defined by operations known as METHODS.

Employee Class Example

  • Name of a class
  • Behaviors(Methods)
  • Get methods :Accessor Methods
  • Set methods: Mutator methods
  • It is good practice to create get and set method in a class

Objects

An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.


                                        // Creating  object
                                        //Classname objectname=new Classname();
                                        Circle object1=new Circle();
                                        Circle object2=new Circle();
                                        Circle object3=new Circle();
     
                                       Employee emp=new Employee();
                                     

                                    

Classes

Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.


                                        public class Employee{
                                        }
                                        
                                     

                                    

Constructor

  • Constructor- a special method used to set up an object when it is originally created.
    • Does not have a return value
    • Has the same name as the CLASS in which it is used
    • If you create a class and do not provide a constructor method, Java will create an empty one by default
    • There won't be any default constructor created by java if you have declared a constructor.
    • Constructors cannot be inherited
  • Classes are constructs that define objects of the same type.
  • A Java class uses variables to define data fields and methods to define behaviors.
  • Additionally, a class provides a special type of methods, known as constructors
  • which are invoked to construct objects from the class.

                  public Employee(){

                  public Employee(String fname, String lname, String phone, Address address, 
                  String SSN){
                    firstName = fname;
                    lastName = lname;
                    phoneNumber = phone;
                    this.address = address;
                    this.SSN=SSN;
                                        
                 }
                                        
              }
                

Default Constructor

A class may be defined without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class.


                        class  Car{

                            public String model;
                            public String color;
                            public int seats;


                          
                           public Car(){
                             System.out.println("In Constructor");
                             model="test";
                             color="red";
                             seats=4;
                        
                          }
                           public void display(){
                            System.out.println("Model" + model);
                            System.out.println("Color" + color);
                            System.out.println("Seats" + seats);
                        
                           }
                        
                        }
                        
                        public class CarExample{
                            public static void main (String [] args){
                            //Do we get error here?
                             Car car=new Car();
                            car.display();
                            Car ferrari= new Car("Ferrari F130","Red",2)
                            ferrari.display();
                        
                            }
                         }
                        

Creating Objects Using Constructors


                    new ClassName();
                    Example:
                    Circle c1=  new Circle(); 
                    Circle c2  new Circle(5.0); 
                    

Declaring Object Reference Variables

To reference an object, assign the object to a reference variable

To declare a reference variable, use the syntax:


                                            ClassName objectRefVar;
                                            Example:
                                            Circle myCircle;
                                            
                                            Classname objectRefVar=new Classname();
                                            Example;
                                            Circel mycircle=new Circle();
                                            
                                    

Accessing Object’s Members

Referencing the object’s data:


                                         objectRefVar.data
                                         e.g., myCircle.radius
                                         arrayName.length

                                    // Invoking the object’s method:
                                    //objectRefVar.methodName(arguments)
                                     e.g., myCircle.getArea()
                                     stringName.length()
                                         
                                    

Employee Class

Code

                                        

SCOPE

  • The SCOPE of data refers to the parts of the program in which the data can be used.
  • Data declared at the CLASS level can be used by all of the methods in that CLASS.
  • This data is known as CLASS or INSTANCE data.
  • Data declared within a Method can only be referenced by that method and is known as LOCAL data.

                    Public Employee(){
                    Private string firstName
                    Public Employee(string fname)
                    {
                        firstName=fname
                    }
                    }
                   

Encapsulation

  • One of the principle attributes of Object Oriented Programming is ENCAPSULATION
  • If we view an OBJECT internally we should be able to see the details of the object’s variables and methods.
  • If we were to view it from outside then we should just see the services it provides and how it interacts with other objects. These services are its INTERFACE.
  • OBJECTS should be self-governing and provide their SERVICES to their CLIENTs through their INTERFACE as though they seem like a black box.

                    Public Employee(){
                    
                    printEmployeeRecord(){
                    }
                }
                   

SETTERS and GETTERS

  • SETTERS or MUTATORS are common methods involved in most classes. It allows a service interface to change data values.setHeight,setData
  • GETTERS or ACCESSORS are a common service method to allow a method to return a variable’s value to a client program. getHeight,getData

                    Public Employee(){
                    
                        public void setFirstName(String value) {
                            firstName = value;
                        }

                        public int getDeptID() {
                            return deptID;
                        }
                    
                    
                }
                   

STATIC

A variable or method that is shared by all instances of a class is called a class variable or class method. You recognize such a variable in Java by the static keyword in the declaration. A static variable will instantiate only one copy of the variable for the whole class instead of a separate copy for each instance of a class. A static variable belongs to a class, not to an instance of the class.

Static variables/methods can NOT access non-static variables/methods!

Static methods can serve as utility methods where you don’t have to declare an object of the class to use the method and all dependencies for the static method can be passed in from the class.

The return Statement

  • The return type of a method indicates the type of value that the method sends back to the calling location
  • A method that does not return a value has a void return type
  • A return statement specifies the value that will be returned
  • Its expression must conform to the return type
  • return expression;

                        Public Employee(){
                        
                            
                        public double getSalary() {
                            return salary;
                        }
    
                        public int getDeptID() {
                                return deptID;
                        }
                        
                        
                    }
                       

Classes

UML Class Diagram

The Date Class

Java provides a system-independent encapsulation of date and time in the java.util.Date class. You can use the Date class to create an instance for the current date and time and use its toString method to return the date and time as a string.


                    java.util.Date date = new java.util.Date();
                    System.out.println(date.toString());
                   // displays a string like Sun Mar 09 13:50:19 EST 2023.

                

Reference Data Fields

The data fields can be of reference types. For example, the following Student class contains a data field name of the String type.


                    public class Student {
                        String name; // name has default value null
                        int age; // age has default value 0
                        boolean isScienceMajor; // isScienceMajor has default value false
                        char gender; // c has default value '\u0000'
                      }
                      

                

Why Data Fields Should Be private?

To protect data.

To make class easy to maintain.


                    public  class StaticPerson {



                        private static String firstName="Shiva";
                        private static String lastName="Sharma";
                    
                        public StaticPerson(String fname, String lname) {
                            fname = firstName;
                            lastName = lname;
                        }
                    
                        public static String getName() {
                            return firstName + " " + lastName;
                        }
                    
                        //setter: Mutator
                        public static void setFirstName(String value) {
                            firstName = value;
                        }
                    
                        static{
                            System.out.println("static block of parent class");
                        }
                    
                   
                    }
                      

                

Example of Data Field Encapsulation

What Class is Immutable?

For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.

Scope of Variables

The scope of instance and static variables is the entire class. They can be declared anywhere inside a class.

The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used.

The this Keyword

The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields.

Another common use of the this keyword to enable a constructor to invoke another constructor of the same class


                        class  Car{

                            public String model;
                            public String color;
                            public int seats;
                           public Car(String model,String color,int seats){
                              model=model;
                             color=color;
                             seats=seats;
                          }

                          public Car(String model,String color,int seats){
                            this.model=model;
                           this,color=color;
                           this.seats=seats;
                        }
                          
                        public void startEngine(){
                            System.out.println("Engine has started");
                        }

                        public void drive(){
                            //what will happen if we remove this keyword?
                            this.startEngine();
                            System.out.println("Car is moving");
                        }

                           public void display(){
                            System.out.println("Model" + model);
                            System.out.println("Color" + color);
                            System.out.println("Seats" + seats);
                        
                           }
                        
                }
    
    
      

Reference the Hidden Data Fields

Calling Overloaded Constructor


                        public class Circle {
                            private double radius;
                         
                        
                            public Circle(double radius) {
                                this.radius=radius;
                             //this must be explicitly used to reference the 
                            // of the object being constructed  data field radius 
                            }
                           
                            public Circle() {
                               this(1.0)
                               //this is used to invoke another constructor
                             
                            }
                            public double getArea(){
                                return this.radius * this.radius * Math.PI;
                              //Every reference variable belongs to an 
                              //instance represented by this.
                            }
                        }
                          
                    
                    

Thank you

Questions/Suggestions