GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing docs.oracle.com — Providing Constructors for Your Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects) Documentation
The Java™ Tutorials
Hide TOC
Providing Constructors for Your Classes
Trail: Learning the Java Language
Lesson: Classes and Objects Section: Classes The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. Providing Constructors for Your ClassesA class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
To create a new Bicycle myBike = new Bicycle(30, 0, 8);
Although public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}
Both constructors could have been declared in You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of You can use a superclass constructor yourself. The You can use access modifiers in a constructor's declaration to control which other classes can call the constructor. Note: If another class cannot call a MyClass constructor, it cannot directly create MyClass objects.
About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.
Previous page: Defining Methods
Next page: Passing Information to a Method or a Constructor |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |