0% found this document useful (0 votes)
11 views

Java Classes/ Objects Class: To Create A Class, Use The Keyword

Uploaded by

kaelasarxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Classes/ Objects Class: To Create A Class, Use The Keyword

Uploaded by

kaelasarxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Object- Oriented Programming

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.

Object-oriented programming has several advantages:

 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:

 The class is only accessible within its own class.


Protected:
 The class is accessible within its own package and by subclasses.

abstract:

 The class cannot be instantiated on its own and must be subclassed.

final:

 The class cannot be subclassed.

Class Creation

Modifiers Classname{
//Attributes
// Methods
}

example:
public class Fruit {

// Attributes
String name;
String color;

}
Explanation:

public class Fruit: This line declares a class named Fruit.


public: This access modifier means that the class can be accessed from other classes.
class: This keyword is used to define a new class.
Fruit: The name of the class. In Java, class names typically start with an uppercase letter.
String name;: This line declares an attribute named name, which is intended to hold the name of the
fruit.
String color;: This line declares another attribute named color, which will hold the color of the fruit

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:

Public class main{

Public static void main(String[] args) {

Fruit f = new Fruit();

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.

Modifier class Classname {

//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.

public class Main {


public static void main(String[] args) {
// Using the no-argument constructor
Fruit defaultFruit = new Fruit(); //

// Using the parameterized constructor


Fruit myFruit = new Fruit("Banana", "Yellow");
myFruit.displayInfo(); // Output: Fruit: Banana, Color: Yellow
}
}
Fruit myFruit = new Fruit("Banana", "Yellow");: This line creates another instance of the Fruit
class using the parameterized constructor.
o The constructor takes two arguments: "Banana" for the name and "Yellow" for
the color.
o The myFruit variable holds the reference to this Fruit object, which now has its
attributes initialized with the provided values.

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:

//Parameterized constructor with two parameters (overloaded constructor)

public Fruit(String name, String color) {

this.name = name;

this.color = color;

System.out.println("Fruityyy"); // Output when parameterized constructor is called }

Parameterized constructor with one parameter (overloaded constructor)

public Fruit(String name) {

this.name = name;

this.color = "Unknown"; // Default value for color

System.out.println("Fruityyy"); // Output when single-parameter constructor is called

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.

public class Classname{

//Private Attributes

Example

public class Fruit{

private String name;


private String color;

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 and Setter


 They allow other classes to read (get) and modify (set) the values of these private fields
while maintaining encapsulation.
 Getters allow you to retrieve the values of private attributes, while setters allow you to
modify them.

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

public String getName () {

return name; // Returns the value of the private attribute 'name'

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) {

this.name = name; // Sets the value of the private attribute '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.

// Parent class (Superclass)


class Fruit {
protected String type = "Fruit"; // Fruit attribute
public void grow() { // Simplified Fruit method
System.out.println("The fruit is growing.");
}
}
// Child class (Subclass)
class Apple extends Fruit {
private String variety = "Granny Smith"; // Apple attribute

public static void main(String[] args) {


// Create an Apple object
Apple myApple = new Apple();

// 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:

Parent Class Fruit:

 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.

Child Class Apple:

 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:

public final void grow() { // Final method

System.out.println("The fruit is growing.");

Explanation:

Final Method (grow()):


 In this code, the method grow() in the Fruit class is marked with the final keyword.

 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 {

public String info(String name) {

return "Fruit: " + name;

// Overloaded method to return information about a fruit with name and color

public String info(String name, String color) {

return "Fruit: " + name + ", Color: " + color;

public String info(String name, String color, double weight) {

return "Fruit: " + name + ", Color: " + color + ", Weight: " + weight + "kg";

public class Main {

public static void main(String[] args) {

// Create a Fruit object

Fruit myFruit = new Fruit();


// Call different versions of the info() method

System.out.println(myFruit.info("Apple")); // Output: Fruit: Apple

System.out.println(myFruit.info("Banana", "Yellow")); // Output: Fruit: Banana,


Color: Yellow

System.out.println(myFruit.info("Orange", "Orange", 1.2)); // Output: Fruit: Orange,


Color: Orange, Weight: 1.2kg

Explanation:

Method Overloading: The Fruit class has three overloaded methods named info(). Each method has a
different number of parameters:

 One that takes only the name of the fruit.

 Another that takes both name and color.

 A third one that takes name, color, and weight.

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:

// Parent class (Superclass)

class Fruit {

public void taste() {

System.out.println("This fruit has a generic taste.");

// Child class (Subclass)

class Apple extends Fruit {


@Override

public void taste() {

System.out.println("The apple is sweet and crisp.");

// Child class (Subclass)

class Lemon extends Fruit {

@Override

public void taste() {

System.out.println("The lemon is sour.");

public class Main {

public static void main(String[] args) {

Fruit myFruit = new Fruit(); // Fruit reference

Fruit myApple = new Apple(); // Fruit reference, but Apple object

Fruit myLemon = new Lemon(); // Fruit reference, but Lemon object

myFruit.taste(); // Output: This fruit has a generic taste.

myApple.taste(); // Output: The apple is sweet and crisp.

myLemon.taste(); // Output: The lemon is sour.

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:

abstract class Fruit { // Abstract method

public abstract void taste(); // Concrete method

public void info() { System.out.println("This is a type of fruit.");

Explanation:

Abstract Class Fruit:

 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.

You might also like