Posts

Showing posts with the label Part F : JAVA Constructors

Java Constructors (Part 2)

Image
Pre-requisites:-  Method Overloading , Inheritance   Copy Constructor  Copy Constructor is a constructor which creates an object by initializing it to the object of the same class which is previously declared.  Writing a Copy Constructor ▪ First a full parameterized constructor is declared so a copy constructor can copy its attributes. ▪ Then an object of that constructor is passed as an argument in copy constructor. ▪ While creating object of parameterized constructor , the same object is passed while instantiating copy constructor. And this will generate copy constructor. Eg:- import java.util.Scanner; public class MyClass { private String name ; private int id ; // normal parameterized constructor MyClass (String name , int id ) { this . name = name ; this . id = id ; } // copy constructor , passing here object 'obj' of normal const. MyClass ( MyClass obj )...

Java Constructor (Part 1)

Image
Java Constructor Constructor in Java is a special-member function. It is used to initialize objects. Constructors are called when objects are created. If the user does not create a constructor , Java has a pre-built constructor that is called when created objects. Rules for creating a Constructor: ▪ The name of the constructor must match the class name. ▪   We can add parameters to a constructor. ▪   The constructor cannot have a return type i.e it is by default void. But we can write return statement in it as it can return class , we will learn about this in future tutorials. There are 3 types of constructors: 1. Default Constructor     If user does not implement a constructor , then when an object is created the Java compiler inserts a default (pre-built) constructor. It does not contain any code in it.   eg:- Code We Write : public class MyClass { public static void main(String[] args) { // creating an object called...