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

V.3.0. - OOP in Java - Get Your Hands Dirty With Code

The document discusses object-oriented programming concepts in Java including object lifecycles, constructors, and overloaded constructors. It explains that objects are created through constructors called with the new keyword. Constructors initialize an object's state before it can be used. The document demonstrates how to declare a reference variable, create an object, and assign the object to the reference. It also shows how to use a no-arg constructor to provide a default value when an object is created without specifying arguments, and how to define multiple constructors to allow objects to be created with or without initializing arguments.

Uploaded by

Iftekharul Islam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

V.3.0. - OOP in Java - Get Your Hands Dirty With Code

The document discusses object-oriented programming concepts in Java including object lifecycles, constructors, and overloaded constructors. It explains that objects are created through constructors called with the new keyword. Constructors initialize an object's state before it can be used. The document demonstrates how to declare a reference variable, create an object, and assign the object to the reference. It also shows how to use a no-arg constructor to provide a default value when an object is created without specifying arguments, and how to define multiple constructors to allow objects to be created with or without initializing arguments.

Uploaded by

Iftekharul Islam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

OOP in Java - Get your hands dirty with code

(Don’t just copy and paste the codes, type the codes like there’s no
tomorrow)
Objects are born and objects die. You are in charge of an object’s lifecycle. You
decide when and how to construct it. You decide when to destroy it (you don’t
actually destroy the object yourself, you simply abandon it and Java GC i.e. Java
Garbage Collector will do the rest).

How object is created?

There are 3 important steps of object declaration, creation and assignment:

Step – 1: Declare a reference variable

Make a new reference variable of a class or interface type.


Human humanOne = new Human();

Human humanOne

Here, humanOne is a reference variable of class Human

Step – 2: Create an object


Human humanOne = new Human();

new Human(): that creates an object

Step – 3: Assign the object to the reference

Assign the new object to the reference.


Human humanOne = new Human();

Assign new Human() to humanOne

Are we calling a method named Human()?

It looks like we’re calling a method named Human(), because of the parentheses.
Actually we are calling the Human Constructor.

A constructor does look and feel a lot like a method, but it’s not a method. A few
are some differences exist:

 A constructor doesn’t have a return type.


 The name of the constructor must be the same as the name of the class.
Unlike methods, constructors are not considered to be members of a class.
(That’s important only when it comes to inheritance)
 A constructor is called when a new instance of an object is created. In fact,
it’s the new keyword that calls the constructor. After creating the object, you
can’t call the constructor again.
public class Human {

public Human() {
// constructor code goes here
}

public void speak() {


// method code goes here
}

The only way to invoke a constructor is with the keyword new followed by the
“class name”.

You can write a constructor for your class (we’re about to do that), but if you don’t,
the compiler writes one for you!

Here’s what the compiler’s default constructor looks like:

public Human() {
// constructor code goes here
}

So what is the definition of constructor?

A constructor has the code that runs when you instantiate an object. In other
words, the code that runs when you say new on a class type.

Every class you create has a constructor, even if you don’t write it yourself.

Key feature of a constructor: it runs before the object can be assigned to a


reference. That means, before anyone can use an object, the object has a chance
to help construct itself.
public class Human {
public Human() {
System.out.println("Hello World!!!");
}
}
public class Earth {
public static void main(String[] args) {
Human humanOne = new Human();
}
}

Uses of constructors:

Mostly used initialize the state of an object i.e. assign values to the object’s
instance variables.
public class Human {
// instance variable
int age;

// constructor
public Human() {
System.out.println("Hello World!!!");
}
}

Using the constructor to initialize important states: What should we do if we


want the programmer who is using “Human” to decide how old a particular Human
should be?

Well, you could add a “setAge()” setter method to the class. But that leaves the
Human temporarily without a age (instance variables do have a default value. 0 or
0.0 for numeric primitives, false for booleans, and null for references), and forces
the Human user to write two statements—one to create the “Human”, and one to
call the “setAge()” method. The code below uses a setter method to set the initial
age of the new Human.
public class Human {
int age;

public Human() {
System.out.println("Hello World!!!");
}

// public void setAge(int age) {


// this.age = age;
// }

//setter method without "this" keyword


public void setAge(int newAge) {
age = newAge;
}
}
public class Earth {
public static void main(String[] args) {
//one to create the Human
Human humanOne = new Human();

//one to call the setAge() method


humanOne.setAge(28);
}
}

Object shouldn’t be used until you’re finished initializing of its state (instance
variables). Let someone make and get a reference to a new Human object that isn’t
quite ready for use that’s not a good idea. How will the Human-user even know that
he’s required to call the setter method after making the new Human?

Solution to this problem is put initialization code is in the constructor. And all you
need to do is make a constructor with arguments.
public class Human {
int age;

// Add an int parameter to the Human constructor.


public Human(int humanAge) {
System.out.println("Hello World!!!");
// Use the argument value to set the age instance variable.
age = humanAge; //this.age = age;
System.out.println("I am " + age + " years old.");
}
}

public class Earth {


public static void main(String[] args) {
// Pass a value to the constructor.
Human humanOne = new Human(28);

}
}

If you write a constructor that takes arguments, and you still want a no-
arg constructor, you’ll have to build the no-arg constructor yourself!

The compiler gets involved with constructor-making only if you don’t say anything
at all about constructors.

Imagine that you want Human users to have 2 options for making a Human—one
where they supply the Human age (as the constructor argument) like before and
one where they don’t specify a age and thus get your default Human age.
You can’t do this cleanly with just a single constructor. Remember, if a method (or
constructor—same rules) has a parameter, you must pass an appropriate argument
when you invoke that method or constructor.

If someone doesn’t pass anything to the constructor, they won’t even be able to
compile without sending an int argument to the constructor call.

So what can you do? Is there any solution?

Not a very good solution: If the parameter value is zero, give the new Human a
default age, otherwise use the parameter value for the age.
public class Human {
int age;

public Human(int humanAge) {


if (humanAge == 0) {
age = 25;
} else {
age = humanAge;
}
System.out.println("I am " + age + " years old.");
}
}

That means the programmer making a new Human object has to know that passing
a “0” is the protocol for getting the default Human age! What if the other
programmer doesn’t know that? Or what if he really does want a zero-age Human
(Assuming a zero-age Human is allowed)? So it might not always be possible to
distinguish between a genuine “I want zero for the age” constructor argument and
a “I’m sending zero so you’ll give me the default age, whatever that is” constructor
argument. That’s why the above solution isn’t very good one!!!

To solve this problem you really need to 2 ways to make a new Human!

You need two constructors. One that takes an int and one that doesn’t. If you have
more than one constructor in a class, it means you have overloaded constructors.
public class AnotherHuman {
int age;

// supply default age


public AnotherHuman() {
age = 25;
}

// use humanAge parameter


public AnotherHuman(int humanAge) {
age = humanAge;
}
}
public class AnotherEarth {
public static void main(String[] args) {
//To make a Human when you know the age:
AnotherHuman humanOne = new AnotherHuman(28);
//To make a Human when you do not know the age:
AnotherHuman humanTwo = new AnotherHuman();
}
}

You might also like