Java Classes/ Objects Class: To Create A Class, Use The Keyword
Java Classes/ Objects Class: To Create A Class, Use The Keyword
OOP stands for Object-Oriented Programming. It is a programming paradigm that uses "objects" to
represent data and functions. In OOP, objects can contain both data (attributes) and methods
(functions) that operate on that data. This approach allows for better organization of code, easier reuse,
and improved maintenance.
OOP is generally faster and easier to execute. While OOP may have some overhead, it often
leads to faster development and easier code management in larger projects. It’s not always the
fastest for small tasks, but its structure makes working on bigger applications more efficient.
It provides a clear structure for programs, improving readability and organization. OOP
organizes code into classes and objects, which makes it easier to understand and work on. It
helps separate different parts of the program, making it easier for teams to collaborate.
It enables the creation of reusable components, leading to less code and shorter development
time. OOP allows you to build components that can be reused across different projects,
speeding up development and reducing the amount of code you have to write.
Tip: The "Don't Repeat Yourself" (DRY) principle aims to minimize code duplication. Identify
common code segments in your application, and consolidate them in a single location for reuse
instead of rewriting them multiple times.
Java
Classes/ Objects
Class
A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors
(methods) that the objects created from the class will have.
To create a class, use the keyword class
Attributes
These are the variables that hold the state or data of the object.
Accessing attributes by creating an object of the class, and by using the dot syntax (.)
Methods
These are functions defined in a class that specify the behaviors of the objects.
Object
An object is an instance of a class. It represents a specific entity created based on the class
blueprint. Each object can have different values for its attributes.
Modifiers
Modifiers define the visibility and behavior of the class.
Common modifiers include:
public:
The class is accessible from any other class.
private:
abstract:
final:
Class Creation
Modifiers Classname{
//Attributes
// Methods
}
example:
public class Fruit {
// Attributes
String name;
String color;
}
Explanation:
Class Intantiation
The process of creating an instance (or object) of a class. This process involves allocating
memory for the new object and initializing its attributes.
Example:
f.name = “Banana”;
f.color = “Yellow”;
f.displayInfo();
Explanation:
Class Structure: The Main class serves as the entry point of the program, while the Fruit class defines a
blueprint for fruit objects.
Object Creation: In the main method, you create an instance of the Fruit class (an object) and initialize it
with specific values ("Banana" for name and "Yellow" for color).
Method Invocation: By calling the displayInfo method on the Fruit object, you utilize the functionality
defined in the Fruit class to show its attributes.
Constructor
A constructor is a special method in a class that is automatically called when an
object (or instance) of that class is created.
Its primary purpose is to initialize the attributes of the object.
Creating constructor
Constructor method are named after their class name.
//Constructor
Classname() {
}
}
Example:
Public class Fruit {
Fruit() {
System.out.println (“ Fruityyy”);
}
}
Explanation:
public class Fruit: This line declares a class named Fruit. The public modifier indicates that the
class is accessible from other classes.
Fruit(): This is the constructor for the Fruit class.
System.out.println("Fruityyy");: Inside the constructor, this line of code prints the string
"Fruityyy" to the console whenever an instance of the Fruit class is created.
Constructor parameter
Is a variable that is passed to a constructor when an object of a class is created. These
parameters allow you to provide specific values to initialize the attributes (or properties) of an
object at the time of its creation.
Constructor Overloading
Allows a class to have more than one constructor with different parameter lists. This means you
can create multiple constructors for a class, each with a different number of parameters or
different types of parameters.
Example:
this.name = name;
this.color = color;
this.name = name;
Explanation:
The parameterized constructor with two parameters public Fruit(String name, String
color) allows the creation of a Fruit object using specified values for both the name and
color attributes, distinguishing it as an overloaded constructor due to its different
parameter list compared to the no-argument constructor. Similarly, the parameterized
constructor with one parameter public Fruit(String name) initializes the name attribute
with the provided value while setting the color to a default value; this too qualifies as an
overloaded constructor because its parameter list differs from the other constructors.
Encapsulation
Ensures that "sensitive" data remains concealed from users. To accomplish this, you should:
Declare class variables or attributes as private.
Provide public getter and setter methods to access and modify the values of these
private variables.
//Private Attributes
Example
Explanation
private String name;: This line declares a private attribute (or member variable) named name of type
String.
private String color;: Similarly, this line declares another private attribute named color of type String.
The private keyword restricts access to the name and color attributes. This means that these attributes
can only be accessed and modified within the Fruit class itself.
Getter Method:
A getter method (also known as an accessor) retrieves the value of a private attribute.
It usually has the following characteristics:
It is declared as public.
It has no parameters.
It returns the value of the private attribute.
Example
Setter Method:
A setter method (also known as a mutator) modifies the value of a private attribute.
It usually has the following characteristics:
It is declared as public.
It takes one parameter (the new value to set).
It does not return a value (declared as void).
Example
public void setName(String name) {
Inheritance
It allows one class, called the subclass or child class, to inherit properties and methods from
another class, known as the superclass or parent class.
To inherit from a class, use the `extends` keyword.
The subclass can:
o Reuse the code from the superclass.
o Extend or modify the inherited behavior.
// Call the grow() method (from the Fruit class) on the myApple object
myApple.grow();
// Display the value of the type attribute (from the Fruit class) and the variety attribute from the Apple
class
System.out.println(myApple.type + " variety: " + myApple.variety);
}
}
Explanation:
The Fruit class defines a general blueprint for fruits, containing an attribute type set to "Fruit"
and a method grow().
The grow() method represents a simple behavior that can apply to all fruits. When called, it
outputs "The fruit is growing." to indicate that the fruit is developing.
The Apple class extends the Fruit class, inheriting the type attribute and the grow() method.
It also defines its own attribute variety, which is set to "Granny Smith" to represent a specific
type of apple.
Final Keyword
If you don't want other classes to inherit from a class, use the final keyword:
Example:
Explanation:
By marking the method as final, it means that this method cannot be overridden by any
subclass. In other words, the Apple class cannot provide a different implementation for grow().
When myApple.grow() is called, it will always execute the version of the method defined in the
Fruit class.
Polymorphism
“Poly”means many and “morph” means take different forms.
It allows objects of different classes to be treated as objects of a common superclass.
Types of Polymorphism:
1. Method Overloading
o Occurs when multiple methods in the same class share the same name but have
different parameter lists
o The method that gets executed is determined at compile time, based on the method
signature (number and types of arguments passed).
class Fruit {
// Overloaded method to return information about a fruit with name and color
return "Fruit: " + name + ", Color: " + color + ", Weight: " + weight + "kg";
Explanation:
Method Overloading: The Fruit class has three overloaded methods named info(). Each method has a
different number of parameters:
Main Class: In the main() method, we create an object of Fruit and call each version of the info() method
with different arguments.
2. Method Overriding
o Occurs when a subclass provides a specific implementation of a method that is already
defined in its superclass.
o The method that gets executed is determined at runtime, based on the type of the object
that is calling the method.
Example:
class Fruit {
@Override
Explanation:
o The Fruit class defines a method taste(), which provides a generic description of the
taste of a fruit.
The Apple class extends the Fruit class and overrides the taste() method to provide a specific
taste description for apples.
o The Lemon class also extends the Fruit class and overrides the taste() method to
describe the taste of lemons.
o In the main() method, we create references of type Fruit for a generic fruit, an apple,
and a lemon.
o When the taste() method is called on each object, the appropriate overridden method
executes, demonstrating runtime polymorphism.
Abstraction
o It focuses on hiding the complex implementation details of a system while exposing only the
essential features to the user.
o It allows developers to handle complexity by breaking down a system into more manageable
pieces and interacting with them at a higher level.
o The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
Example:
Explanation:
The Fruit class is declared as an abstract class, meaning it cannot be instantiated directly.
It contains an abstract method taste(), which must be implemented by any subclass that
extends Fruit.
It also has a concrete method info() that can be inherited by subclasses, providing general
information about fruits.