Ok I am trying to wrap my head around this:
Write an application that creates a class for the student object with the following attributes:
Student Number, Name, Address, Phone No., and Course.
Write a test program that sets and gets each attribute in the class.
The test program should also display all of the attributes in the class.
Using the student class and its attributes from the previous question, write an application (extend the previous program) that includes both a user-defined and default constructor.
Write a test program to demonstrate the use of both constructors.
This is a work-sheet from college, for some revision on Objects in Java.
The part that troubles me is the one where it asks to have both user-defined and default constructor?
I was under impression it was impossible to do it? Because if you don't provide a constructor yourself, JVM will provide one (default constructor?). But if you define any constructor, then default one becomes unavailable?
Is this just poorly worded task, or could it mean something else?
I'm pretty sure whoever created the work-sheet meant "No-arg constructor" instead of "Default constructor".
You can't technically create the Default constructor (since this is done for you by the compiler), but you can explicitly create the no-arg constructor (which functionally is the same).
So, yes, poorly worded task.
In java, when you don't explicitly specify a constructor, the compiler will add a "default" constructor: a constructor thar doesn't take parameters. If you specify a constructor, then the compiler doesn't add that constructor.
For instance, this code will compile fine:
class Student {
String name;
int age;
// ...
}
// ...
Student myself = new Student();
But this code wont compile:
class Student {
String name;
int age;
// ...
public Student(String name) {
this.name = name;
}
}
// ...
Student myself = new Student(); // compilation error: use new Student("Jhon Smith");
Because the default constructor is not available any more.
Java provide default constructor when you dont implement yourselve one. But when you create customized constructor you have to implement also default if you would like to use constructor with no arguments. Let's asume we have class A{} for java it will looks like that:
public class A{
public A(){//auto generated constructor
}
}
but if you provide an customized constructor auto generated constructor dissapear.
Default constructor is not created when programmer provides any constructor. But here I'm expecting that the author of this task understands "default" constructor as the one without any parameters.
Concluding you would have two constructors:
public class MyClass {
public MyClass () {
}
public MyClass (long studentNumber, String name, String address....) {
}
Above is correct, however, in OO terms, "default constructor" is a constructor that takes in no arguments. The other type of constructor is one where arguments are taken into the constructor to make things custom.
ie:
Student(){ //default constructor
number = 0;
name = "bob";
//etc etc
}
student(int nm, int nm, etc etc){ //parametrized constructor
number = nm;
name = nm;
//etc etc
}
According to Charatan & Kans, Java in Two semesters 3rd Edition, page 196:
Constructor just like any methods can be overloaded, meaning within a single class we can have 2 or more constructors, where one take 1 argument like:("studentName") and within the same class, another constructor might take 2 arguments ("studentName", " studentId"), yet another constructor still within the same class may have 3 arguments ("studentName", "studentId", " studentPhoneNumber").
This is Constructor Overloading. Here's an example:
public class student {
// attributes
private String studentName;
private int studentID;
private int studentPhoneNumber;
// constructor with one argument
public student (String studentNameIn) {
studentName = studentNameIn;
}
// constructor with 2 arguments
public student (String studentNameIn, int studentIdIn) {
studentName = studentNameIn;
studentID = studentIdIn;
}
// constructor with 3 arguments
public student (String studentNameIn, int studentIdIn, int studentPhoneNumberIn) {
studentName = studentNameIn;
studentID = studentIdIn;
studentPhoneNumber = studentPhoneNumberIn;
}
// default constructor REINSERTED no argument
public student () {}
// methods
}
The above is a clear example of constructor overloading. Now during the OBJECT creation, meaning when the student object is being created, it will be up to the programmer to utilise the constructor he/she chooses, with 0 arguments ( default that was REINSERTED) or with 1 argument again he/she may choose the constructor that contains 2 arguments etc. Its a matter of choice and requirement of user.
No superclass or multiple class is needed as constructor can be overloaded as demonstrated above.
Related
I'm working through a past exam for a computer science paper and have become slightly confused on this part here.
The instructions are to write a class book(done), which has two data fields(also done) a constructor which initializes the two values (done as well) and a constructor which replaces the default constructor (no clue what this is about). I've researched it and gone through my lab notes but I can't understand what they're asking.
Here's the code
public class Book{
//here's the two data fields
int pages;
String title;
public Book (int pageNum, String titleString){//here's the constructor to set the values
pages = pageNum;
title = titleString;
}
}
//so where's the other constructor that replaces the default constructor supposed to go?
I think following points mean same thing, which you have already done.
1.which has two data fields(also done) a constructor which initializes the two values
2.constructor which replaces the default constructor (no clue what this is about)
By default class has default constructor. like this
public Book()
{
}
If write some parameterised constructor, then default constructor will be replaced. By seeing through your code , you have already written parameterised constructor.
It seems they want something like this :
public Book() {
this(0, "");
}
I have noticed a thing that a constructor and a simple method of a class do the same work. what is the exact reason to create a construct of a class? If i create MyClass(){} constructor and MyClassMethod(){} method it will do the same work as I write the body part of those method and constructor. So what is the need of construct? Does it have any special use ?
A constructor and a method are two different things. The fact that you can write the same or similar code inside them is irrelevant.
When a new object is created a constructor is called. If you don't specify one the compiler will create a default one for you. This is the place where initializaton of the object's fields takes place and memory is allocated for the object. This is a concept that all object-oriented languages have. A new object must be initialized somehow. Memory needs to be allocated. In Java you don't manage the memory yourself (at least not directly anyway) so this is the purpose of the constructor. Note that since a constructor is always executed, this behaviour is enforced as soon as you call e.g. Person p = new Person();.
Now since a constructor is always being called, you have an option here: do you let the default constructor execute or do you create one yourself? Perhaps there are fields that need to be initialized in a way other than their default values. Or perhaps you need to not allow creating an object without providing some values. If you define a constructor yourself, the compiler does not create a default one for you. So if I have public Person(String firstName, String lastName) {} then I have created a specific rule that is again enforced by the system: a new object of class Person cannot be created unless you give a first name and last name:
Person p = new Person(); // this would give a compile error
Person p = new Person("John", "Smith"); // this is the only way to create an object now
Using a method you cannot enforce this. The programmer using your class might call your method or not. The constructor is a part of the lifecycle of the object. Methods define the behaviour of the object
Some points :
1) Constructors are the only way to set final instance variables .
public class SomeType {
final int x ;
SomeType(int y){
x=y;
}
}
2) A class with private constructor cannot be sub classed.
3) If your class is a subclass and the base class doesn't have a default constructor , then you need a constructor in your class to call the super class constructor.
One of the benefits of using a constructor over a method is that you can be assured the constructor was called and the work within the constructor was performed.
The language specifies that to construct an object a constructor must be called. So if you use a custom method to establish the initial state of your object, you will need to call the default constructor first. Why make two method calls when you can perform the work in one call the constructor and be assured the object has been properly initialized?
public class Test(){
private Integer x;
public Test(){
}
public Test(Integer x){
this.x = x;
}
public void setX(Integer x){
this.x = x;
}
public void doSomethingWithX(){
this.x.toString();
}
}
Test test = new Test(8);
test.doSomethingWithX(); //I know x has been declared and assigned
Test test = new Test();
test.doSomethingWithX(); //X has not been assigned results in NPE
If you create a new Object of MyClass it will automatically call the constructor - you can initialize all members within it, and be sure that this object´s members are all initialized.
Generally:
A constructor is always called once when you create a new Object of this class, and you can´t call it manually.
And don´t do "real" work in a constructor, as it will slow down the creation of objects of this class - only initialize your class/members there.
You can also use different constructors, depending on your needs - but if you create a constructor, there is no more default constructor!
Example:
public MyClass {
int score;
public MyClass(int sc) { // already know the score
score = sc;
}
public MyClass() { // don´t know the score yet
score = 1;
}
public void addScore() {
score += 5; // i know for sure that score is not zero
}
}
Essentially a constructor is just a special method that implicitly returns an object of its containing type. You should generally use constructors for creating objects - this is what people expect to see.
However, there is a useful idiom called the factory method (more info at this link) which is essentially using a static method to construct an object, the key advantages being
You can give a factory method a more descriptive name (whereas of course a standard constructor has to be named after the containing class).
They don't have to return an object, giving more flexibility.
They can return a sub-types of the class.
You can set final fields without initializer in a constructor. This helps to build immutable instances:
class Number extends Expr {
private final int n;
public Number(int n) {
this.n = n;
}
public int getValue() {
return this.n;
}
}
So after a constructor like this, you can rely on the fact that the instance is initialized completely (and in this case, it's values are immutable/constant).
Constructor is not like simple methods. It is called every time when the object of that particular class is created. You don't need to call it explicitly.
There are somethings that we need to do immediately when the object is created, for instance when you create a GUI kind of thing you want to set many properties on the time of creation like size of window etc.
Another benefit of constructor is security of class. You cannot create a object unless you know the right perimeters of constructor.
More details:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type.
Some points :
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
These are the benefits of constructors.
Automatic initialization of objects at the time of their declaration.
Multiple ways to initialize objects according to the number of
arguments passes while declaration.
The objects of child class can be initialised by the constructors of base class.
This question already has answers here:
How to avoid constructor code redundancy in Java?
(4 answers)
Closed 9 years ago.
Hi I am just learning about constructor chaining in Java and had some questions...
First of all could someone please explain when I would ever need to use this? Off the top of my head I seriously cannot think of a situation.
In this example, within the constructor with no arguments I call another constructor. How do I access this new "James Bond" object for future use?
import java.util.*;
class Employee
{
private String name;
private double salary;
public Employee()
{
this("James Bond", 34000);
}
public Employee(String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public static void main(String[] args)
{
Employee a = new Employee();
}
}
Actually I believe the most common use of chained Constructors is when the Constructor does more than just setting the member variables.
static int numOfExamples = 0;
public Example(String name, int num)
{
this.name = name;
this.num = num;
numOfExamples++;
System.out.println("Constructor called.");
Log.info("Constructor called");
}
public Example()
{
this("James Bond",3);
}
That way we don't have to write the code for logging and incrementing the static variable twice, instead just chaining the constructors.
Chaining constructors like this is useful to avoid repeating code, and helps with maintainability:
public MyClass(int x, double y, String z) {
// set fields
}
public MyClass() { // i.e. a constructor that uses default values
this(42, 4.2, "hello world"); // x is 42, y is 4.2, and z is "hello world"
}
If we didn't use the chain, and wanted to change how the x argument (for example) is processed when constructing an instance of MyClass, we would have to change code in both constructors. With the chain, we only need to change one of them.
1) As others have said, it's for code maintenance, basically the idea is that you only write one piece of code once, which means you only need to edit it once, there is no risk of overlooking something when editing your methods and the two accidentally becoming different.
Personally I tend to use this differently than in your example. Like so:
Employee() {
setupStuff();
}
Employee(String name) {
this();
this.setName(name);
}
This is a nice way of doing things, because potentially your setter can be way more complicated than just setting a member in the class. So basically what this does is puts calling the empty constructor and then a setter into a single method, making it much easier for anyone using the class.
2) The constructor being called doesnt't create a different object at all, it creates this object. Note that there is no new keyword used. Basically you're just calling a different method inside your constructor, except that method happens to also be a constructor.
Every time you want to allow constructing an object wit default values, and also want to allow creating the same object with non-default values. Let's imagine a DateTime class. You could want to initialize it with the current time by default, or with a specific time. Imagine a Car class. You could imagine constructing it with Black as the default color, or with a specific color. This kind of situation is very common. See java.util.ArrayList or java.util.Locale, for concrete examples.
It's stored in the name field. So you access it, from the object itself, with this.name (this being optional, just as in the getName() method).
How do I access this new "James Bond" object for future use?
Because you saved the values of name and salary as fields of your employee class, then inside the employee class you can use those fields, and outside your employee class you can use the getter/setter methos of your employee class
public class Country implements ICountry {
int stability = 2;
}
Country poland = new Country(stability = 3);
What I'm trying to do is extend an interface(ICountry) with a new class("Country") that has a few default values. I want to know if it's possible to redefine some of those defaults when creating a new instance of the Country class. The last line of code in my example is what I currently have as my attempt to accomplish this, but my IDE is warning me that 'stability cannot be resolved to a variable'.
My questions is, is it possible to redefine some of an object's default values when instantiating a class without constructing a method?
I'm just starting to learn Java and Android programming on my own, so if you think I referred to something with the wrong terminology please correct me.
What you want is to define a constructor of Country that accepts a parameter and assigns it to a field, like so:
public class Country implements ICountry {
int stability = 2; // the default
public Country() {
// no parameters, no assignments
}
public Country(int stability) {
// declares parameter, assigns to field
this.stability = stability;
}
}
You can then create multiple instances of this class, like this:
Country unitedKingdom = new Country(); // 2 is the value of stability, taken from the default
Country poland = new Country(3); // 3 is the value of stability
The reason you need to have two constructors is that the version with no parameters (the "default", or "implicit" constructor) is generated if you haven't specified one, but once you specify a constructor, it won't be generated any more.
An alternate, and equivalent syntax for the default constructor could be:
public class Country implements ICountry {
int stability; // declare field, but don't assign a value here
public Country() {
this.stability = 2; // instead assign here, this is equivalent
}
}
Both this version and the previous version of the default constructor result in the same effect, but is generally a matter of preference.
There are languages that use the syntax you have shown, they're called "named parameters", but Java doesn't have them.
This is what overloaded constructors are for:
public Country(int stability)
{
this.stability=stability;
}
I have a question regarding this in the following code. In the following, this.name will set the name. We could also do this using name = name, so my question is should the this pointer be used. This is not an homework
import java.io.*;
public class Employee{
String name;
int age;
String designation;
double salary;
//This is the constructor of the class Employee
public Employee(final String name){ //EDIT: Made parameter final
this.name = name;
//name= name; this is also correct
}
//Assign the age of the Employee to the variable age.
public void empAge(int empAge){
age = empAge;
}
//Assign the designation to the variable designation.
public void empDesignation(String empDesig){
designation = empDesig;
}
//Assign the salary to the variable salary.
public void empSalary(double empSalary){
salary = empSalary;
}
//Print the Employee details
public void printEmployee(){
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}
// name= name; this is also correct
This is not correct. It'll assign your parameter to itself. By using the this keyword, you're declaring which name you're using (i.e. the field on your Employee object).
You may wish to name the field differently from the parameter. However this means that all works well until someone automatically refactors your code to (perhaps inadvertently) declare the field and parameter as the same name!
For this reason you'll often see method signatures defined thus:
public Employee(final String name)
The final keyword prevents reassignment, and stops you from mistakenly reassigning the input parameter, and consequently not assigning to your field. Note also that if you declare the field as final, then compilation will fail if you don't make an assignment to that field. Using final is a good way to trap such errors and also enforce the immutability of an object (often a good thing - it contributes to a more reliable solution, especially in a threaded environment).
Well to avoid the confusion in cases like u mentioned name=name we uses this pointer to make it clear the we here mean class variable name .
So to make understand the reader here in this case we use this though there can be many other cases where (this) is more useful.
In some compilers name=name gives error as well
Notice that there are two things called name in your code. Your class Employee has member variable called name, and the constructor takes a parameter that's also called name.
What you want to do in the constructor is set the member variable name to the same value as the parameter name. To access the member variable, you have to use this.name, because name refers to the parameter - because the variables have the same name, the parameter is hiding the member variable.
Note that name = name; does not do the same thing as this.name = name;.
When you do name = name;, you assign the value of the parameter name to the parameter itself - not to the member variable. The compiler does not magically know that the first name is supposed to mean the member variable, and the second name is supposed to mean the parameter.
So, you need this in this case to refer explicitly to the member variable, instead of the parameter that is hiding the member variable.
In this case this is just a scope resolution/disambiguation.
public Employee(String name){
this.name = name;
// the above line will assign a value of parameter to instance variable
// name= name; this is also correct
// (**NO** the above line will assign a value of parameter to itself)
}
When the parameter name and your class variable names are same, then to differentiate between them, you write this.classVariable to identify the class variale
When you call a variable, the pointing one is the one who is the closest to your current scope.
So, if program is currently containing in memory a local variable toto and the wrapping class containing a field variable toto, you have to precise this keyword in order to access the field's one.
Otherwise, the field variable is said to be shadowed by the local variable and so doing toto = toto assigns the local parameter to itself (never useful) and not what you are expecting => the field variable.
Why make it so hard on yourself?
Just rewrite the signature/method like this:
public Employee(String _name) {
name = _name;
}
Always try to avoid variable hiding or other hard-to-read constructs. If you want your code to be maintainable, write it in such a way that everybody can understand it immediately. Even if you are the only one; you might forget what you meant in time.
This Keyword Program
public class ThisKeywordActivity extends Activity {
int a=20;
public ThisKeywordActivity(int a) { // this();
//this.a = a;
}
public ThisKeywordActivity()
{
System.out.println(" msg default Constructor ");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_this_keyword);
ThisKeywordActivity thisKeywordActivity2 = new ThisKeywordActivity(100);
thisKeywordActivity2.show(40);
}
public void show( int a)
{
System.out.println("msg a 2==="+a);
System.out.println("msg a 3==="+this.a);
}
}
Output
a2=40
a3=20