Test Anatomy of a class

classes and objects have the same relation as blueprints to a house

In Java, a class is a blueprint or a template for creating objects which has different attributes and behaviors. Every Java class has a specific structure or anatomy that includes various components.

Here are the different components of a Java class:

Class declaration: Every Java class begins with the declaration of the class name, which should be unique within the package. The syntax for declaring a class is as follows:

public class ClassName {
    // Class body
}

Class body: The class body is enclosed in braces {} and contains various components that define the behavior and attributes of the class. The class body consists of the following components:

a. Fields or Instance Variables: Fields are variables that store the state or data of the object, this was covered in unit 2. They can be initialized at the time of declaration or in the constructor. Fields can be of any primitive(int) or reference type(Strings). They are a essential component of a class

public class Person {
    String name;
    int age;
    double height;
    String Race;
}

Methods: Methods are functions that define the behavior of the object. They can be used to perform certain actions or return a value. Methods can take arguments and can be overloaded, which means there can be multiple methods with the same name but different parameter types. Here's an example:

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    
    public double add(double a, double b) {
        return a + b;
    }
}

Constructors are special methods that are used to initialize the state of the object. They have the same name as the class and do not have a return type, by initializing the state of a object the constructor is essentially establishing the field variables

Here's an example:

public class Person {
    String name;
    int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Not it is important to understand that any field variables, methods, or constructers listed as public is accesible outside the class whereas when it is listed private it is only accesible within the class

public class MyClass {
    // This variable can be accessed from anywhere.
    public int publicVar;

    // This variable can only be accessed from within this class.
    private int privateVar;

    // This method can be accessed from anywhere.
    public void publicMethod() {
        System.out.println("This is a public method.");
    }

    // This method can only be accessed from within this class.
    private void privateMethod() {
        System.out.println("This is a private method.");
    }
}

-Now generally classes are always made public because it needs to be used

-fields are usually private so that it cannot be tampared with outside the class,

  • most methods are going to be public but there will be scenarios where you want to make it private,

-Constructers need to be public because when creating an object you need to make it public

Accessor methods, also known as getters, are a type of class method that allows access to the value of an object's attributes. They are used to retrieve the value of a private or protected attribute without allowing direct modification.

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return this.name;
    }
    
    public int getAge() {
        return this.age;
    }
}

In this example, we have a Person class with private attributes name and age. We provide public getter methods getName() and getAge() to allow access to these private attributes. The getName() method returns the name attribute as a String, and the getAge() method returns the age attribute as an int. These methods are used to retrieve the values of the attributes without allowing direct modification from outside the class.

Mutator methods, also known as setter methods, are a type of class method that allows modification of an object's attributes. They are used to update the value of a private or protected attribute from outside the class. Here's an example of a mutator method in Java:

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
}

In this example, we have a Person class with private attributes name and age. We provide public setter methods setName() and setAge() to allow modification of these private attributes. The setName() method takes a String argument and updates the name attribute, and the setAge() method takes an int argument and updates the age attribute. These methods are used to update the values of the attributes from outside the class.

HACKS:

Exercise 1: Create a Rectangle class with width and height fields, and getArea() and getPerimeter() methods. Then create a Square class that extends the Rectangle class and has a sideLength field.

Exercise 2: Create a Person class with firstName and lastName fields, and a getFullName() method. Then create a Student class that extends the Person class and has a major field and a getMajor() method.

Exercise 3: Create an Animal class with a speak() method that prints "I am an animal." Then create a Cat class and a Dog class that extend the Animal class and

5.6 Writing Methods

Format

The typical format of a method header is (). Access modifiers for Java methods can be: public, private, or protected. Return type can be: void, String, boolean, int, double, float, char, etc. Method name can be anything, but usually something descriptive that allows you to infer what the method does. You can have any number of parameters or no parameters.

When a member is declared as "public," it can be accessed from anywhere, including from other classes, even if they are in different packages or assemblies. This means that the member is accessible by any code that can access the class that contains the member.

class Person {
    public int getAge() {
        return age;
    }
    // other class members
}

class Main {
    public static void main(String[] args) {
        Person person = new Person();
        int age = person.getAge();
        // use the age
    }
}


// Examples of method headers:
public static void main (String args[])
private String sayHello ()
protected static int addNums (int a, int b)
public void printSum (double a, double b, int c, boolean flag, String text)

5.7 Static Variables and Methods

Static variables and methods are marked by the keyword static, which means that these are properties of the entire class and not just of one particular object.

  • Static methods cannot access or change the values of instance variables.
  • Static methods do not have a this reference and cannot use instance variables or call non-static methods.
public class College {
    // Static variable to store the number of students enrolled in the college
    public static int numberOfStudents = 0;

    // Static method to enroll a student
    public static void enrollStudent() {
        numberOfStudents++;
    }

    public static void main(String[] args) {
        // Enroll some students
        College.enrollStudent();
        College.enrollStudent();
        College.enrollStudent();

        // Print the number of students enrolled
        System.out.println("Number of students enrolled: " + College.numberOfStudents);
    }
}

5.8 Scope and Access

There are two types of scope: local scope and global scope.

Local scope means that a variable can only be used inside a particular method or constructor and not outside. These include our method and constructor parameters and also any variables we declare inside the method or constructor.

Global scope means that a variable or method can be used outside that method or constructor and at least throughout that class. These include our instance variables and also the methods that we write for our class. We declare these directly in the class and not inside a method or constructor.

If there is a local variable (usually a parameter) and a global variable (usually an instance variable) in the same method with the same name, the local variable takes precedence.

public class College {
    // Global variable to store the number of students enrolled in the college
    public static int numberOfStudents = 0;

    public static void main(String[] args) {
        // Local variable to store the number of students enrolled in a specific course
        int numberOfStudentsInCourse = 10;

        // Print both variables
        System.out.println("Number of students in college: " + numberOfStudents);
        System.out.println("Number of students in course: " + numberOfStudentsInCourse);

        // Call a method that uses both variables
        enrollStudentsInCourse(5);
    }

    public static void enrollStudentsInCourse(int numberOfNewStudents) {
        // Access global and local variables
        System.out.println("Number of students in college inside method: " + numberOfStudents);
        int numberOfStudentsInCourse = 15;
        System.out.println("Number of students in course inside method: " + numberOfStudentsInCourse);

        // Enroll new students in course
        numberOfStudentsInCourse += numberOfNewStudents;

        // Update global variable
        numberOfStudents += numberOfNewStudents;

        // Print updated values
        System.out.println("Number of new students enrolled in course: " + numberOfNewStudents);
        System.out.println("Total number of students in course: " + numberOfStudentsInCourse);
        System.out.println("Total number of students in college: " + numberOfStudents);
    }
}

This demonstrates that the global variable has global scope, which means it can be accessed from anywhere in the code, while the local variable has local scope, which means it can only be accessed within the method in which it was defined.

5.9 This Keyword

The this keyword is a keyword that essentially refers to the object that is calling the method or the object that the constructor is trying to make. There are three ways to use this:

  • To refer to an instance variable This will solve the problem of having duplicate variable names. To distinguish the instance and local variables, we use this.variableName for the instance variable and simply variableName for the local variable.

  • As a parameter Sometimes, we can also use the object as a parameter in its own method call to use itself in the method by using objectName.methodName(this).

  • As a constructor or method call This will allow us to overload our constructors effectively. Inside the overloaded constructors, we can make a call to the full constructor using this() where the parameters include the default values as well. We can also use this way as a method call to call a method inside a method call as well using this.methodName().

public class College {
    private String name;

    public College(String name) {
        this.name = name;
    }

    public void printName() {
        System.out.println("College name: " + this.name);
    }

    public void setName(String name) {
        this.name = name;
    }
}