Monday, June 20, 2016

Constructor

Constructor is a special method that is defined in the class and will be called automatically whenever there is an instance of an object. Constructor itself serves to initialize the value of the data contained in the relevant class. If we do not define a constructor in the class that we created, Java will make it for us automatically. This kind of constructor is called default constructor. The default constructor initializes all the data with zero values. However, once we define a new constructor for a class that we created, then the default constructor is not not used anymore. Just as method, constructor can have parameter and can also be overloaded.

Keep in mind that the constructor does not have a return value, not even void. This is because implicitly the actual type of the return of the constructor is the type of the class itself. Constructor name must exactly match with the class name. Here is a sample program that demonstrates a constructor for class Box:

class Box {

   double length;
   double width;
   double height;

   //Define constructor for class Box
   Box() {
      length = 4;
      width = 3;
      height = 2;
   }

   double calculateVolume() {
      return (length * width * height);
   }
}

class DemoConstructor1 {
   
   public static void main(String[] args) {

      Box b1, b2;

      b1 = new Box();
      b2 = new Box();

      System.out.println("Volume b1 = " + b1.calculateVolume());
      System.out.println("Volume b2 = " + b2.calculateVolume());
   }
}

In the above program, we set the initial value for the data length, width, and height each with value 4, 3 and 2. This would apply to any establishment of Box object. Here is the result that will be given by the program:

Volume b1 = 24.0
Volume b2 = 24.0

Initialization process using this way can still be said to be less dynamic. Because, every time the creation of the object box, the value of which is used as the initial value is always 4, 3, and 2. To make the constructor is more dynamic, then we can put parameter, as shown in the following program example:

class Box {

   double length;
   double width;
   double height;

   //Define constructor with parameter
   Box(double l, double w, double h) {
      length = l;
      width = w;
      height = h;
   }

   double calculateVolume() {
      return (length * width * height);
   }
}

class DemoConstructor2 {
   
   public static void main(String[] args) {

      Box b1, b2;

      b1 = new Box(4, 3, 2);
      b2 = new Box(6, 5, 4);

      System.out.println("Volume b1 = " + b1.calculateVolume());
      System.out.println("Volume b2 = " + b2.calculateVolume());
   }
}

This time, we created constructor that using parameter. This causes the initial value can be dynamic depending on the value ​​that are passed during the creation of the object. Consider the following code:

b1 = new Box (4, 3, 2);
b2 = new Box (6, 5, 4);

The first line shows that we do initialization length with value 4, width with value 3, and height with value 2. The second line we initialize the data length, width, and height of each with 6, 5 and 4.

31 comments:

  1. The Construction Industry offers some of the best opportunities and the hardest, most challenging work available, for Commercial Cleaning vendors. Construction site clean up projects can, and if structured correctly, will prove to be the most lucrative aspect of a commercial cleaning business. They can also prove to be the hardest work, the biggest headaches and a scheduling/staffing nightmare. آرین سازه

    ReplyDelete
  2. Once you got yourself out of the phone and finally in the auto repair shop, it's imperative that you know the type of auto repair mechanics/technicians you'll be dealing with. Knowing their style and what they're all about when it comes to getting your car problem repaired, is crucial. Chemical Hose

    ReplyDelete
  3. Ideas, Ideas, Ideas, Ideas, Ideas! That's what this report is all about. This series of related real estate tales is written specifically to get your motor running and your wheels turning. mortgage risk assessment

    ReplyDelete
  4. The Construction Industry offers some of the best opportunities and the hardest, most challenging work available, for Commercial Cleaning vendors. Construction site clean up projects can, and if structured correctly, will prove to be the most lucrative aspect of a commercial cleaning business. They can also prove to be the hardest work, the biggest headaches and a scheduling/staffing nightmare. رحلة كروز

    ReplyDelete
  5. Expansion and รับทาสีอาคาร of building components in commercial, industrial and residential buildings. Is your building plagued with peeling paint, moisture intrusion or even mold?

    ReplyDelete
  6. Very good publish, thanks a lot for sharing. Do you happen to have an RSS feed I can subscribe to? buy steroids USA

    ReplyDelete
  7. Mattress shopping can be stressful. So many people learn the hard way not to buy just any old mattress. Perhaps you have heard that Tempur-Pedic mattresses are good, and you are not sure which one would work best for you. Being stuck with the wrong mattress for a couple of years is not something anyone wants to do. Best beds

    ReplyDelete
  8. The article discusses how detailed and unambiguous retail construction drawing sets can help moderate-budget retail projects, which use design-bid-build delivery methods, to avoid change orders and increase project profitability. Also highlighted is the key role that such retail construction drawing sets play in helping all the parties involved, including the architects, designers, and contractors. Towing Company Lake Charles LA

    ReplyDelete
  9. Go for a plumbing company that will give you value for your money. If they quote a high price, ensure that they breakdown the expenses for you. Companies that quote high prices should be those that use the newest plumbing technology in dealing with all your plumbing problems. If a plumbing company quotes a considerably lower price for the service, be sure that the service may not be as good as you would want it to be. Cheap is always expensive. plumbers new orleans

    ReplyDelete
  10. Working in a construction site has a lot of dangers and risks. This is because being a construction worker, you will need to do a lot of dangerous works such as cutting, riveting, sawing, building, and all other sorts of industrial activities. No matter how technically advanced the safety measures and work protocols are, there will always be a possibility that an accident will happen. asphalt repair New Caney

    ReplyDelete
  11. If you have any desire to move beyond goldfish and guppies and into the exciting world of saltwater reef aquariums, you are going to have to tackle the basics of plumbing your aquarium. Many of the invertebrates you work with in a reef aquarium require a strong flow of water running constantly through the setup. This water movement is critical for the exchange of oxygen and carbon dioxide, as well as removing waste products produced by live coral and other creatures you may have in your aquarium. plumbers in park city utah

    ReplyDelete
  12. The first real step towards becoming a professional plumber is undertaking the relevant plumbing courses. Plumbing requirements are varied and emergencies like burst pipes can happen in all setups, business and domestic areas alike. Basically there are three types of plumbing courses that you could enroll into Online Plumbing Courses These types of courses can be applied over the internet. plumbing draper utah

    ReplyDelete
  13. Plumbing contractors are the right people to approach when a homeowner wants to install a new kind of plumbing system at his home; on the other hand, they can help at a new home that someone is building where he or she needs state of the art plumbing services. It is quite often a headache to the homeowner when there are plumbing problems at home. There might be a leaky tap or a broken pipe that plumbing contractors can fix within minutes. Plumbers Layton Utah

    ReplyDelete
  14. When it comes to seeking out a company to take care of your plumbing problems, you will need to do a number of things if you want to make sure that you find the very best services available. One thing you can be certain of is that there are a considerable amount of plumbing companies out there, and the reason for this is that the services they offer tend to be in very high demand. Just about anyone who owns a home will experience a problem with their plumbing system at some point in time, and while it is certainly... Provo Plumber Utah

    ReplyDelete
  15. At Tampa Bay Pavers in Tampa, Fl. we set your vision in stone. We offer the highest quality paving products and services at the most affordable price. We specialize in custom designs and expert installation of paver driveways, patios, pool decks, walkways, summer kitchens, fire pits and much more. Come see why we are the fastest growing pavers in Tampa Florida Tampa Pavers

    ReplyDelete
  16. Construction In Dubai And Abu Dhabi Has A Great Potential For The Ones Who Are Gravely Willing To Double Their Money Overnight. Plenty of ongoing constructions reveal the growth and stability of property business in a country and the world witnessed a huge construction projects in Dubai and ADhabi mainly. interior design

    ReplyDelete
  17. With any construction project, there are typically numerous crucial details to consider. Many of these can have an impact on the quality of the structure, the speed in which the project is accomplished, and the overall cost. For first time construction managers, all these details can quickly become overwhelming. By hiring a construction consultant however, you can avoid many of the pitfalls that plague so many inexperienced construction managers. Such professionals will be familiar with every step of the construction process, and they will be able to help you avoid any problems that you might encounter during the project. home additions

    ReplyDelete
  18. Local Landscaping Cranbourne is your premium local landscaping service in Cranbourne and the surrounding area. Our services include Landscape and Garden Design, Landscape Construction, Landscape Water Features, Landscape Lighting Installation, Landscape Maintenance Service, Gardening Service, Lawn Care Installation and Maintenance Services, including the area around your driveway. No job is too big or too small for your Cranbourne landscaping requirements. Call Local Landscaping Cranbourne today to discuss your requirements on (03) 5910 3000 Cranbourne Landscaping

    ReplyDelete
  19. Construction projects are major endeavors that involve a lot of equipment - those heavy machinery used to transport and move large materials, and a lot people - the construction workers. The larger the construction project, the greater the number of equipment and people is needed. Is a diesel repair shop for commercial trucks and roadside service

    ReplyDelete
  20. The Construction Industry offers some of the best opportunities and the hardest, most challenging work available, for Commercial Cleaning vendors. Construction site clean up projects can, and if structured correctly, will prove to be the most lucrative aspect of a commercial cleaning business. They can also prove to be the hardest work, the biggest headaches and a scheduling/staffing nightmare. homes for sale lakewood ranch

    ReplyDelete
  21. Working in a construction site has a lot of dangers and risks. This is because being a construction worker, you will need to do a lot of dangerous works such as cutting, riveting, sawing, building, and all other sorts of industrial activities. No matter how technically advanced the safety measures and work protocols are, there will always be a possibility that an accident will happen. Free Quote

    ReplyDelete
  22. It is a common fact that we find a wide variety of construction machines on every construction sites, which make the construction jobs easy, safe and quicker. Depending on the application, construction machines are classified into various categories which we are discussing here. https://www.myhandymanannarbor.com/

    ReplyDelete
  23. The construction industry is growing at a rapid pace every day. Private and government investments are making it a booming market of the day. Even public investments have been incorporated into the scenario today which only makes the industry bigger. ann arbor handyman services

    ReplyDelete
  24. The Construction Industry offers some of the best opportunities and the hardest, most challenging work available, for Commercial Cleaning vendors. Construction site clean up projects can, and if structured correctly, will prove to be the most lucrative aspect of a commercial cleaning business. They can also prove to be the hardest work, the biggest headaches and a scheduling/staffing nightmare. concrete contractors grand rapids

    ReplyDelete
  25. The construction industry is growing at a rapid pace every day. Private and government investments are making it a booming market of the day. Even public investments have been incorporated into the scenario today which only makes the industry bigger. Visit our site

    ReplyDelete
  26. So why does a construction company need a video of their project? Let's look at it from a pure marketing perspective. 1) Video is a great inbound marketing tactic. 55+ Retirement Concierge Services

    ReplyDelete
  27. Everyday, thousands people all across America make the decision to begin the process of buying a home, or decide to put their current home up for sale. chinese money plant

    ReplyDelete
  28. The construction and management consultants are basically known as the representatives of a construction estate. They work at an expert level along with the ordinary builders. There is also a senior construction team working at a side which makes sure that proper amount and quality of material is being used by the builders. This team also ensures that whether the material being used is good for the health of the environment or not. Tow Truck Company

    ReplyDelete
  29. The Construction Industry offers some of the best opportunities and the hardest, most challenging work available, for Commercial Cleaning vendors. Construction site clean up projects can, and if structured correctly, will prove to be the most lucrative aspect of a commercial cleaning business. They can also prove to be the hardest work, the biggest headaches and a scheduling/staffing nightmare. new construction

    ReplyDelete
  30. Thank You for Sharing valuable information with us.

    E-Commerce is the fastest-growing platform which is becoming more demandable day by day this is a tremendous form of the vibrant sector that is bringing several opportunities to the new generation to become more skilled and professional. Taking up this great advantage in the E-Commerce sector would need the right path and the right skillset you need to learn the latest technologies and high-demand skills such as building payment gateways and developing an accessible and easy website along with the basics of E-commerce that‘s why Aptech learning official Pro E-Commerce training program in Dwarka, Janakpuri, and Gurgaon which will help to make a successful career in this booming industry. Java Programming Course helps to become an expert in Java web application development. It helps you to bring efficiency in collecting and analyzing the data through Java programming in this course you will learn effective web UI/UX design and Secure web applications by using the advanced technologies of the Java program.

    For more details please visit our website : Aptech Dwarka

    ReplyDelete