[OOP 2] Constructors, Packages, Static, Final, Modifiers, In-built Methods
- in JAVA ☕
📗Attributes in Java
🆗! 🤗 Have you ever wondered what an attribute is? 🤔 Well, let me tell you, class attributes are simply variables within a class that holds data. You can also call them fields! 💻
public class LivingBeing {
int eyes;
int nose;
int legs;
}
Here eyes
nose
and legs
are attributes!
👋In our last article, we talked about accessing attributes in OOP. Let's recap: To access attributes, you need to create an object of the class and use the dot syntax (.) to access them.
Here's the code snippet for better understanding:
public class LivingBeing {
int eyes;
int nose;
int legs;
String soundType;
void sound() {
System.out.println("I make this " + this.soundType + " sound!");
}
}
You can also modify attribute values Or overwrite existing values:
public class Main {
public static void main(String[] args) {
LivingBeing human = new LivingBeing();
human.eyes = 2;
human.nose = 1;
human.legs = 2;
human.soundType = "Tamil";
human.sound();
}
}
◼To restrict the ability to overwrite existing values, you can declare the attribute as final
:
public class Main {
final int num = 10;
public static void main(String[] args) {
Main obj = new Main();
obj.num = 20;
System.out.println(obj.num); // Error 🐞
}
}
🪨This will give us an error🪲!
📗Final keyword in Java
🔸By adding final
before a field declaration, you can prevent its contents from being modified. Essentially, it turns it into a constant! Remember that you must initialize a final field (💡remember, an attribute can also be called a field 😊) when it is declared. It's a common coding convention to use all uppercase letters for final fields, like:
final int NO_OF_EYES = 2;
🔸Unfortunately, using final only guarantees immutability when instance variables are primitive types, not reference types (ie, objects). If an instance variable of a reference type has the final modifier, reference will never change, but the value of the object itself can.
📘Finalize Method
Now, let's move on to the finalize()
method. 🗑️
🔸In Java, when an object is about to be reclaimed by the garbage collector, you can define specific actions that will occur by using the finalize()
method. By adding a finalizer to a class, you can define code that runs when an object is just about to be reclaimed by the garbage collector.
🔸To create a finalizer for a class, you just define the finalize()
method. The Java run time calls that method whenever an object of that class is about to be recycled. Just before the asset is freed, the Java run time calls the finalize() method on the object.
public class Example {
private int id;
public Example(int id) {
this.id = id;
}
public void finalize() {
System.out.println("Object with id " + id + " is being garbage collected.");
}
public static void main(String[] args) {
Example e1 = new Example(1);
Example e2 = new Example(2);
// Set e1 to null, so that it becomes eligible for garbage collection
e1 = null;
// Force garbage collection
System.gc();
}
}
📗Static
Modifier in Java
Let's talk about static members in Java! 🤓
🤔 When Java runs a program, it looks for a specific function called main()
to start the program. But why do we need to declare main()
as static
?
👉 When we declare a method or variable as static
, it means that it belongs to the class itself, rather than to any instance of the class. In other words, a static
method or variable can be accessed using the class name, rather than through an object of the class. 🏠
An example here;;;;
🚀 The main
function is the entry point of a Java program, and it needs to be accessible without creating an instance of the class. Therefore, we declare it as static
, so that it belongs to the class itself and can be called using the class name. 🏃♂️
🤔 If we didn't declare the main
function as static
, we would need to create an instance of the class before we could call it, like this:
public class MyClass {
public void main(String[] args) {
// ...
}
}
MyClass obj = new MyClass();
obj.main(args);
🙅♂️ But since main
is the entry point of the program, we can't create an instance of the class before calling it. Therefore, we declare it as static
, so that we can call it directly using the class name: 🎉
public class MyClass {
public static void main(String[] args) {
// ...
}
}
MyClass.main(args);
🔸A static method in Java belongs to the class and not to the object. Also, it's important to note that a static method can only access static data. It cannot access non-static data or instance variables. Non-static members, on the other hand, belong to an instance (ie. Object), which means that they're meaningless without resolving which instance of a class you're referring to. In a static context, you don't have an instance, which is why you can't access a non-static member without explicitly mentioning an object reference.
🔸In fact, you can access a non-static member in a static context by specifying the object reference explicitly. 🪨 For Example,
public class Human {
String message = "Hello World";
public static void display () {
System.out.println(Human.message);
}
public static void main(String[] args) {
Human mithin = new Human();
mithin.message = "Mithin's message";
Human.display();
}
}
📗Constructors in Java
🆗! Let's talk a little about Constructors()
in Java! 🤓
🔸Constructor in Java is a special method that is used to initialize objects. It decides what happens when an object is created. It can be used to set initial values for object attributes.
🔸So, once a constructor is defined in a class, it is automatically called when an object of that class is created, even before the new operator completes. It's like a method that gets executed when an object is instantiated (Yeah! it's spelt correctly 😊). Constructors are used to initialise the object's state with default or user-defined values.
🔸Constructors look a little strange because they have no return type, not even void. This is because the implicit return type of a class, the constructor is the class type itself. So, when you call a constructor, it creates an instance of the class and returns a reference to that instance.
For example, let's say you are creating a Person
class in Java that represents a person with a name and an age. To create a new Person
object, you would need to call the Person
constructor, which is defined using the Person()
syntax. Here's an example:
public class Person {
private String name;
private int age;
public Person() {
this.name = "Mithin Dev";
this.age = 18;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters for the fields...
}
In this example, the Person
constructor initializes a new Person
object with default values of "Mithin Dev" for the name and 18 for the age. This means that if you create a new Person
object without providing any arguments, it will be initialized with these default values:
Person mithin= new Person();
System.out.println(mithin.getName()); // Output: "Mithin Dev"
System.out.println(mithin.getAge()); // Output: 18
However, you can also provide specific values for the name
and age
fields by using a constructor that takes arguments. For example:
Person mithin= new Person("Mithin Dev", 18);
System.out.println(mithin.getName()); // Output: "Mithin Dev"
System.out.println(mithin.getAge()); // Output: 18
When you create an object of a class, the constructor is called to initialize its attributes. If you don't define a constructor for a class, Java creates a default constructor for you, but it won't allow you to set initial values for object attributes.
By creating your own constructor, you can set initial values for object attributes.
What are the differences between constructors and methods in Java?
Did you know that every class in Java has at least one constructor? 🤔 And unlike methods, constructors have the same name as the class in which they are defined.
Another key difference is that constructors do not have a return type, while methods do. In fact, you can use the "void" keyword to indicate that a method does not return any value. 😎
But perhaps the most significant difference is when they are called. Constructors are only called once, at the time of object creation, while methods can be called any number of times. 🤓
📗Modifiers in Java
📘Access Modifiers in Java
🤔What are Access Modifiers in Java?
🔸I bet you're quite familiar with the public
keyword that appears in almost all of our examples, right? 🤔
🔸Well, just in case you need a quick refresher, the public
keyword is an access modifier!🚪It's used to set the access level for classes, attributes, methods, and constructors.
🔸We usually divide modifiers into two groups:
👀Access Modifiers
👀Non-Access Modifiers
🔸Access Modifiers, as the name suggests, are used to control the access level of a certain class, attribute, method, or constructor. On the other hand, Non-Access Modifiers don't control access levels, but they provide other useful functionalities. 😎
🔸For classes, we have two access modifiers: public
and default
. If you use public
, the class is accessible by any other class (including different packages). But, if you use default
, the class is only accessible by classes in the same package.
🔸Now, for attributes, methods, and constructors: we have four access modifiers to choose from: public
, private
, default
, and protected
. If you use public
, the code is accessible for all classes. However, if you use private
, the code is only accessible within the declared class. If you use default
, the code is only accessible in the same package. And finally, if you use protected
, the code is accessible in the same package and subclasses.
📘Non-Access Modifiers in Java
🆗! Now, Let's talk about non-access modifiers in Java.
🔸There are several non-access modifiers you can use in Java to provide additional functionality to your classes, attributes, and methods.
📕For classes
🔒 Final Classes: When a class is declared as final, it means that it cannot be extended or inherited by any other class. It is a way to ensure that the implementation of a particular class remains the same throughout the program and cannot be changed.
For example, let's say you have a final class called Math
that contains static methods for mathematical calculations. You could declare the Math
class as final to ensure that its implementation remains constant and cannot be extended or overridden:
public final class Math {
public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
// Other static methods for mathematical calculations...
}
🎨 Abstract Classes: When a class is declared as abstract, it means that it cannot be instantiated on its own, but can only be extended by other classes. It's like a blueprint for other classes to follow.
For example, let's say you have an abstract class called Shape
that defines the basic properties and methods of a shape, such as its colour and size. You could then create concrete classes like Circle
and Square
that extend the Shape
class and provide their own implementation of the properties and methods:
public abstract class Shape {
String color;
int size;
public Shape(String color, int size) {
this.color = color;
this.size = size;
}
public abstract double area();
public abstract double perimeter();
}
public class Circle extends Shape {
public Circle(String color, int size) {
super(color, size);
}
public double area() {
return Math.PI * Math.pow(size / 2, 2);
}
public double perimeter() {
return 2 * Math.PI * (size / 2);
}
}
public class Square extends Shape {
public Square(String color, int size) {
super(color, size);
}
public double area() {
return size * size;
}
public double perimeter() {
return 4 * size;
}
}
📕For Attributes and Methods
There are several non-access modifiers you can use. The final
modifier means that the attribute or method cannot be overridden or modified. The static
modifier means that the attribute or method belongs to the class, rather than an object. The abstract
modifier can only be used on methods and can only be used in an abstract class. The transient
modifier means that the attribute or method is skipped when serializing the object containing them. The synchronized
modifier means that the method can only be accessed by one thread at a time. Finally, the volatile
modifier means that the value of an attribute is not cached thread-locally and is always read from the "main memory".
🔸I hope this helps you understand the different non-access modifiers you can use in Java! Let me know if you have any questions. 😊
You might not understand it properly now, but you will!, once become familiar with abstraction and inheritance. 🆗?
📗Packages and API in Java
Java packages are like gift boxes 🎁 that you can use to organize your code. They are a way to group related classes together, making it easier to manage and maintain your codebase.
Think of it like putting all your books 📚 on a bookshelf. By organizing your code into packages, you can easily locate and use specific classes when you need them.
📦 When you create a package, you can add classes and interfaces to it, which helps to keep your code organized and easier to manage. You can even create sub-packages within a package to further organize your code.
💻 Packages also provide a way to manage access control in Java. By default, classes within a package have access to each other, but classes outside of the package cannot access those classes. This helps to prevent unintended changes to the code and maintains encapsulation.
👥 Packages can also be used for sharing code across different projects or teams. By exporting a package, you can make it accessible to other programs and even allow other developers to use your code in their own projects.
🔍 When you write import statements in your code, you are telling Java which packages or classes you want to use in your program. This helps to avoid naming conflicts and makes your code more readable.
📘Built-in Packages in Java
Let's talk about built-in packages in Java! 🤓
🔸So, did you know that the Java API contains a vast library of prewritten classes that you can use in your programs? These classes are included in the Java Development Environment, and they're free to use! 😎
🔸This library has components for managing input, database programming, and many more features. You can find the complete list of these classes on Oracle's website: docs.oracle.com/javase/8/docs/api.
🔸The library is divided into packages and classes. You can either import a single class with its methods and attributes or a whole package that contains all the classes belonging to that package.
🔸To use a class or package from the library, you need to use the import
keyword. So, what do you think? Are you excited to try out some of these built-in classes? 🤔
import package.name.Class; // To import a single class
import package.name.*; // To import the whole package
📘User-defined Packages in Java
🔸To create your own package, you just need to keep in mind that Java uses a file system directory to store packages, just like folders on your computer.
🔸For example, let's say you want to create a package called "MyPackage" and you want to store a class called "MyPackageClass" in it. You would create a directory called "MyPackage" and then create a file called MyPackageClass.java inside that directory.
🔸So your directory structure would look like this:
📂 root
└── 📂 MyPackage
└── 🗒️MyPackageClass.java
🔸To create the package, you just need to add the package
keyword at the top of your "MyPackageClass.java" file, like this:
package MyPackage;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
And that's it! Now you have your very own package called MyPackage
that contains the class MyPackageClass
. 😃
📗Conclusion
The article explains various concepts in Java programming, including attributes, the final keyword, the finalize()
method, static members, and constructors. Attributes are simply variables within a class that holds data. By adding final
before a field declaration, you can prevent its contents from being modified, essentially turning it into a constant. The finalize()
method allows you to define specific actions that will occur when an object is about to be reclaimed by the garbage collector. When a member is declared static, it can be accessed even before any objects of its class are created, and without any reference to an object. Finally, constructors are used to initialise the object's state with default or user-defined values, and they are automatically called when an object of that class is created.
Thank You Soo Much for your valuable time.😊🥳👋
👋 Hi there! Let's connect and collaborate!
Here are some ways to reach me:
🔹 GitHub: github.com/mithindev
🔹 Twitter: twitter.com/MithinDev
🔹 LinkedIn: linkedin.com/in/mithin-dev-a-397983247
Looking forward to connecting with you!