Classes and Objects
A class is a type that is defined by the user in a programming language. It serves as a blueprint or template that describes both the data (attributes) and the behaviour (methods) that objects of that class will possess.
In object-oriented programming, objects are instances of a class. When a class is instantiated, an object of that class is created, which has its own set of attributes and can perform actions based on the methods defined in the class.
To understand it better, you can think of a class as a blueprint for a specific type of object. It defines the properties or characteristics (attributes) that an object of that class will have, such as its name, size, colour, etc. Additionally, it also defines the actions or operations (methods) that the object can perform, such as calculating a value, displaying information, or interacting with other objects.
By using classes, developers can organize and structure their code more efficiently. They can create multiple objects of the same class, each with its own unique set of attribute values, while still sharing the same behaviour defined by the class's methods.
Class declaration in Java follows a specific syntax. Here is the syntax for declaring classes in Java:
<modifier>* class <class_name> {
<attribute_declaration>*
<constructor_declaration>*
<method_declaration>*
}
Let's break down the different components of the class declaration syntax:
Following the syntax, here's an example of a class declaration in Java:
java:
public class Counter {
private int value;
public void inc() {
++value;
}
public int getValue() {
return value;
}
}
In this example, we define a class called Counter
with a private attribute value
, a method inc()
to increment the value and a method getValue()
to retrieve the current value. The class is declared as public
, which means it can be accessed from other classes. The attribute is private
, limiting its access to only the class itself.
Attributes in OOP represent the data or properties of an object, while methods define the actions or behaviours that an object can perform. Attributes store information, and methods perform operations on that information. They work together to define the structure and behaviour of objects in object-oriented programming.
When declaring attributes in Java, you can use the following syntax:
<modifier>* <type> <attribute_name>[= <initial_value>];
Let's break down the different parts of the attribute declaration syntax:
<modifier>
: This represents an optional modifier that specifies the access level or other properties of the attribute. It can be public
, private
, protected
, or no modifier (default access).<type>
: This specifies the data type of the attribute, such as int
, float
, String
, or any other valid Java data type.<attribute_name>
: This is the name given to the attribute. It should follow the naming conventions, such as starting with a letter and using a camel case.= <initial_value>
: This is an optional part that allows you to initialize the attribute with a default value. The initial value is assigned to the attribute when an object of the class is created.Here are some examples of attribute declarations in Java:
java:
public class Foo {
private int x;
private float f = 0.0f;
private String name = "Anonymous";
}
In the above example, the class Foo
declares three attributes: x
, f
, and name
. The x
attribute is declared without an initial value, so it will be assigned the default value for its data type (0
for int
). The f
attribute is declared with an initial value of 0.0f
, indicating a floating-point value. The name
attribute is declared with an initial value of "Anonymous"
, specifying a string value.
Remember to specify the appropriate data type for each attribute and provide an optional initial value if necessary.
When declaring methods in Java, you can use the following syntax:
<modifier>* <return_type> <method_name>(<argument>*){ <statement>* }
Let's break down the different parts of the method declaration syntax:
<modifier>
: This represents an optional modifier that specifies the access level or other properties of the method. It can be public
, private
, protected
, or no modifier (default access).<return_type>
: This specifies the data type of the value that the method returns. It can be a primitive type (e.g., int
, float
) or a reference type (e.g., String
, Object
) or void
if the method does not return any value.<method_name>
: This is the name given to the method. It should follow the naming conventions, such as starting with a letter and using a camel case.<argument>*
: This represents zero or more arguments or parameters that the method accepts. Each argument is specified with a data type and a name. Multiple arguments are separated by commas.<statement>*
: This includes the statements or code that define the functionality of the method. It represents the logic or operations that the method performs.Here are some examples of attribute declarations in Java:
java:
public class Counter {
public static final int MAX = 100;
private int value;
public void inc() {
if (value < MAX) {
++value;
}
}
public int getValue() {
return value;
}
}
In the above example, the class Counter
declares two methods: inc()
and getValue()
. The inc()
the method does not have a return type (void
) and does not accept any arguments. It increments the value of the Counter
object if it is less than the maximum value. The getValue()
method returns a int
value and does not require any arguments. It retrieves the current value of the Counter
object.
By declaring methods within a class, you define the behaviour or actions that objects of the class can perform. These methods can access the class's attributes and manipulate them as needed. Methods are invoked on an object using dot notation, where the object reference is followed by the method name and any required arguments.
Remember to specify the correct return type, method name, and argument list for each method, and include the necessary statements to define the functionality of the method.
An object in object-oriented programming (OOP) is a specific instance of a class that combines attributes (data) and methods (behaviours) defined by its class, representing a real-world entity.
To access members (attributes and methods) of an object in Java, you use the following syntax:
<object>.<member>
For example, consider the following class "Counter" with attributes and methods:
public class Counter {
public static final int MAX = 100;
private int value = 0;
public void inc() {
if (value < MAX) {
++value;
}
}
public int getValue() {
return value;
}
}
To access the members of an object of the "Counter" class, you first create an instance of the class using the `new` keyword:
Counter c = new Counter();
Then, you can access the members of the object `c` using the dot operator (`.`). For example:
c.inc(); // Accesses the method 'inc()' of the 'Counter' object 'c'
int i = c.getValue(); // Accesses the method 'getValue()' of the 'Counter' object 'c'
/* C language */
struct Date { int year, month, day;};
/* C language */
Date d; d.day = 37; //invalid day d.month = 2;
d.day = 30; // invalid data d.day = d.day + 1; //No check
To enforce information hiding, you should modify the access modifiers of the internal data fields to private. Here's an updated version of the solution in Java:(solution)
/* Java language */
public class Date {
private int year, month, day;
public void setDay(int day) {
// Add validation logic here
this.day = day;
}
public void setMonth(int month) {
// Add validation logic here
this.month = month;
}
public void setYear(int year) {
// Add validation logic here
this.year = year;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
}
/* Java language */
Date d = new Date();
d.setDay(37); // Invalid day, validation can be added in the setter method
d.setMonth(2);
d.setDay(30); // Invalid day, validation can be added in the setter method
/* Java language */ public class Person { private String name; private int age; public void setName(String name) { this.name = name; } public void setAge(int age) { if (age >= 0) { this.age = age; } else { System.out.println("Invalid age value"); } } public String getName() { return name; } public int getAge() { return age; } }
/* Java language */ Person person = new Person(); person.setName("John Doe"); person.setAge(25); System.out.println("Name: " + person.getName()); // Output: Name: John Doe System.out.println("Age: " + person.getAge()); // Output: Age: 25
Constructors:
[<modifier>] <class_name>(<argument>){<statement>*}
Here's an example demonstrating constructor overloading:
/* Java language */
class Codemummy {
private int myInt;
private double myDouble;
//constructor
public Codemummy() {
myInt = 5;
myDouble = 5.0;
}
}
Constructors have the following characteristics:
- Role: The main role of a constructor is to initialize the object's data members and set up its initial state.
- Name: The name of the constructor must be the same as the name of the class. This is how the compiler identifies the constructor when it is called.
- Return type: Constructors do not have a return type, not even void. They are automatically called when an object is created and cannot be explicitly called like regular member functions.
- Default constructor: If you don't explicitly define a constructor for a class, the compiler will generate a default constructor for you. The default constructor takes no arguments and initializes the object's data members to their default values (e.g., 0 for numeric types, null for pointers, etc.).
- Accessibility: Constructors are usually declared as public so that they can be called from anywhere in the program. However, constructors can also be declared private, making them accessible only within the class itself. Private constructors are often used in design patterns like the singleton pattern.
- Multiple constructors: A class can have more than one constructor, and they can be overloaded with different parameter lists. This allows for creating objects with different initializations or providing flexibility when creating objects.
Default Constructor:
Constructor overloading:
/* Java language */
class Codemummy {
private:
int myInt;
double myDouble;
public:
// Default constructor
Codemummy() {
}
// Constructor with one parameter
Codemummy(int intValue) {
myInt = intValue;
myDouble = 0.0;
}
// Constructor with two parameters
Codemummy(int intValue, double doubleValue) {
myInt = intValue;
myDouble = doubleValue;
}
};
int main() {
Codemummy obj1; // Calls the default constructor
Codemummy obj2(5); // Calls the constructor with one parameter
Codemummy obj3(10, 3.14); // Calls the constructor with two parameters
return 0;
}
points:
Packages:
Package statement:
package <top_pkg_name>[.<sub_pkg_name>]*;
/* Java language */
package java.lang;public class String { // ...}
import <pkg_name>[.<sub_pkg_name>]*.*;or
import <pkg_name>[.<sub_pkg_name>]*.<class_name>;
No comments