Classes and Objects

Estimated reading: 10 minutes 227 Views

Creating a Class in Java using NetBeans:

Classes are like blueprints that define the structure and behavior of objects in Java. Think of them as templates for building specific objects with unique properties and abilities.

In Apache NetBeans, follow these steps to create a new class:

Project Setup:

  1. Go to File > New Project > Java Application.
  2. Name your project (e.g., JavaOOP) and click Finish.

Package Creation:

  1. Navigate to the Source Packages section.
  2. Click the + sign and choose New > Java Package.
  3. Name your package (e.g., com.mycompany.javaoop) and click Finish.

Class Creation:

  1. Right-click on the package you created.
  2. Select New > Java Class.
  3. Name your class (e.g., Main) and click Finish.

Code:

package com.mycompany.javaoop;

public class Main {
    public static void main(String[] args) {
        System.out.println("JAVA");
    }
}

Explanation of the Code:

– package com.mycompany.javaoop;: This line specifies the package where your Main class belongs. Organizing classes into packages helps maintain code structure and avoid naming conflicts.
– public class Main: This declares a public class named Main. Public classes can be accessed from other parts of your project.
– public static void main(String[] args): This is the main method, the entry point where your program execution begins.
– System.out.println(“JAVA”);: This line prints the string “JAVA” to the console.

Troubleshooting and Tips:

<No main classes found> Error: If you encounter this error, ensure you’ve set the Main Class field in your project’s Run configuration to com.mycompany.javaoop.Main.

Here’s how to address the “No main classes found” error in NetBeans:

  1. Right-click on the project name (in this case, “JavaOOP”) in the Projects window.
  2. Select Properties.
  3. Go to the Run category.
  4. In the Main Class field, enter the fully qualified name of your main class, including the package name. For example, if your class is named “Main” and it’s in the package “com.mycompany.javaoop”, you would enter com.mycompany.javaoop.Main.
  5. Click OK to save the changes.

Now try running your code again. It should execute without the “No main classes found” error.

Creating Classes and Objects:

Separate Files for Separate Classes: Each class in Java needs its own file, distinct from the Main class. This promotes organization and modularity in your code.

Creating the Car Class:

  1. Right-click on the package where you want to create the new class (e.g., com.mycompany.javaoop).
  2. Select New > Java Class.
  3. Name the class Car (capitalizing the first letter is a Java naming convention).
  4. Click Finish. This generates a new file named Car.java within your package.

Naming Convention for Classes:

  • Always start class names with a capital letter.
  • Use descriptive names that reflect the class’s purpose (e.g., Car, Person, Account).
  • This convention makes your code more readable and easier to understand.

Example 1:

class Car {
    String name;
    int maxSpeed;
    float price;
    int model;
}

Class Declaration:

  • class Car – This line declares a new class named Car.

Attributes:

  • String name; – This defines an attribute named name of type String. It will store the name of the car object.
  • int maxSpeed; – This defines an attribute named maxSpeed of type int. It will store the maximum speed of the car object in kilometers per hour.
  • float price; – This defines an attribute named price of type float. It will store the price of the car object in a floating-point format.
  • int model; – This defines an attribute named model of type int. It will store the model year of the car object.

Now we will create our instances for Car class in the Main class, because it is the entry point of the program where execution starts.

public class Main
{
    public static void main(String args[]) {
        Car c1 = new Car();
        c1.name = "Tesla";
        c1.maxSpeed = 210;
        Car c2 = new Car();
        c2.name = "Kia";
        System.out.println(c1.name);
        System.out.println(c1.maxSpeed);
        System.out.println(c2.name);
    }
}

This code still uses the Car class with attributes like name, maxSpeed, price, and model.
Main Class:

  • public static void main(String args[]): This line remains the entry point of your program.
  • Car c1 = new Car();: This line creates a new instance of the Car class and assigns it to the variable c1.
  • c1.name = “Tesla”;: This line sets the name attribute of the c1 object to “Tesla”.
  • c1.maxSpeed = 210;: This line sets the maxSpeed attribute of the c1 object to 210 kilometers per hour.
  • Car c2 = new Car();: This line creates another new instance of the Car class and assigns it to the variable c2.
  • c2.name = “Kia”;: This line sets the name attribute of the c2 object to “Kia”.
  • System.out.println(c1.name);: This line prints the value of the name attribute of the c1 object to the console, which should output “Tesla”.
  • System.out.println(c1.maxSpeed);: This line prints the value of the maxSpeed attribute of the c1 object to the console, which should output “210”.
  • System.out.println(c2.name);: This line prints the value of the name attribute of the c2 object to the console, which should output “Kia”.

Example 2:

Car Class:

class Car { 
    String name; 
    int maxSpeed; 
    float price; 
    int model;
    
    void setName(String n) {
        name = n;
    }
    String getName() {
        return name;
    }
}
  • It has four attributes: name, maxSpeed, price, and model. These attributes are not shown in this example, but they could store information about a car’s name, maximum speed, price, and model year.
  • It also has two methods:
    – setName(String n): This method takes a string argument n and sets the car’s name attribute to that value.
    – getName(): This method returns the current value of the car’s name attribute as a string.

Main Class:

public class Main
{
    public static void main(String args[]) {
        Car c1 = new Car();
        c1.name = "Tesla";
        c1.setName("KIA");
        System.out.println(c1.getName());
    }
}
  • It creates a new instance of the Car class and assigns it to the variable c1.
  • It sets the car’s name attribute to “Tesla” using the direct assignment (c1.name = “Tesla”).
  • Then, it overwrites the name by calling the setName method with the argument “KIA”. This method changes the internal name attribute of the c1 object.
  • Finally, it prints the car’s name using the getName method, which retrieves the current value (“KIA”) and prints it to the console.

Example 3:

Class Car:

class Car { 
    String name; 
    int maxSpeed; 
    float price; 
    int model;
    
    void setName(String n) { // Setters/ Mutators
        name = n;
    }
    String getName() {       // Getters/ Accessors
        return name;
    }
    void setModel(int m) {
        if(m >= 2015)
            model = m;
        else
            System.out.println("Sorry, we do not accept this model");
    }
    int getModel() {
        return model;
    }
}
  • Attributes: It still has name, maxSpeed, price, and model.
  • Methods:
    – Setters: These methods allow setting specific attribute values.
    – setName(String n): Sets the name attribute.
    – setModel(int m): Sets the model attribute with a validation check, only accepting years 2015 or later.
    – Getters: These methods retrieve specific attribute values.
    – getName(): Returns the name attribute value.
    – getModel(): Returns the model attribute value.

Main Class:

public class Main
{
    public static void main(String args[]) {
        Car c1 = new Car();
        c1.name = "Tesla";
        c1.setModel(2021);
        System.out.println(c1.getModel()); // 2021
    }
}
  • Car c1 = new Car();: Creates a new Car object.
  • c1.name = “Tesla”;: Sets the name attribute of c1 using the default behavior (no setter needed).
  • c1.setModel(2021);: Sets the model attribute of c1 using the setter. Since 2021 is valid, it updates the model.
  • System.out.println(c1.getModel());: Prints the model attribute of c1, which should output “2021”.

Access Level Modifiers in Java

(Controlling Visibility and Encapsulation)

Access level modifiers are fundamental constructs in Java that determine the visibility and accessibility of class members (fields, methods, constructors). They play a crucial role in promoting encapsulation, a core principle of object-oriented programming that ensures data protection and modularity.

Key Concepts:

  • Visibility: Refers to whether a class member is directly visible and usable from other parts of your code.
  • Accessibility: Refers to the ability to directly access a class member without using special mechanisms.

Types of Access Level Modifiers:

  1. Public:
    Members declared public are visible and accessible from anywhere in your program.
    Use this modifier judiciously for elements that need to be widely used, but be cautious not to expose implementation details unnecessarily.
  2. Private:
    Members declared private are only visible and accessible within the class where they are defined.
    This promotes encapsulation by restricting direct access to internal data, encouraging the use of public methods to control interactions with the class.
  3. Protected:
    Members declared protected are visible and accessible within the class where they are defined, its subclasses in the same package, and subclasses in different packages (but not directly from other classes in different packages).
    This modifier is useful for creating a base class (superclass) with protected members that can be accessed and potentially overridden by its subclasses, promoting code reuse and inheritance.
  4. Default (Package-Private):
    Members declared without any access modifier are visible and accessible within the same package (the package containing the class definition).
    This provides a balance between visibility and access control within a package.

Example 4:

This code effectively demonstrates fundamental object-oriented concepts like encapsulation, access modifiers, and object interaction in Java. It provides a solid foundation for building more complex and robust Java applications.

Car Class:

public class Car { 
    private String name; 
    private int maxSpeed; 
    private float price; 
    private int model;
    
    public void setName(String n) { // Setters/ Mutators
        name = n;
    }
    public String getName() {       // Getters/ Accessors
        return name;
    }
    public void setModel(int m) {
        if(m >= 2015)
            model = m;
        else
            System.out.println("Sorry, we do not accept this model");
    }
    public int getModel() {
        return model;
    }
}
  • Attributes:
    – name: Private String storing the car’s name.
    – maxSpeed: Private int storing the car’s maximum speed.
    – price: Private float storing the car’s price.
    – model: Private int storing the car’s model year.
  • Methods:
    – setName(String n): Public setter to set the car’s name.
    – getName(): Public getter to retrieve the car’s name.
    – setModel(int m): Public setter to set the car’s model year, including validation for years 2015 or later.
    – getModel(): Public getter to retrieve the car’s model year.

Main Class:

public class Main
{
    public static void main(String args[]) {
        Car c1 = new Car();
    c1.setModel(2021);
    System.out.println(c1.getModel()); // 2021
    }
}
  • Car c1 = new Car();: Creates a new Car object named c1.
  • c1.setModel(2021);: Attempts to set the model of c1 to 2021. This succeeds because 2021 is a valid year.
  • System.out.println(c1.getModel());: Prints the model of c1 to the console, which outputs “2021”.

Key Points:

  • Encapsulation: The Car class encapsulates its data using private attributes, ensuring controlled access through public methods.
  • Data Validation: The setModel method includes validation to prevent invalid model years, promoting data integrity.
  • Object Interaction: The Main class demonstrates how to create a Car object and interact with it using its public methods.
  • Setters and Getters: These methods provide a controlled way to modify and retrieve object attributes, upholding encapsulation principles.

Data Hiding

Data Hiding is a software development technique specifically used in object-oriented programming (OOP). Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes.

Why do we use this technique?
Because we could have many object that will connect through messages and use each other methods.

Encapsulation
Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

To achieve encapsulation in Java:

  • Declare the variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.
Share this

Classes and Objects

Or copy link

CONTENTS
English