Create a default constructor in Java - java

I need to create a method with a default constructor, which sets name to an empty string and sets both credits and contactHours to zero. How to do it? Thanks, Pieter.

Methods don't have constructors... classes do. For example:
public class Dummy
{
private int credits;
private int contactHours;
private String name;
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
// More stuff here, e.g. property accessors
}
You don't really have to set credits or contactHours, as the int type defaults to 0 for fields anyway.
You're likely to want at least one constructor which takes initial values - in which case your parameterless one can delegate to that:
public class Dummy
{
private String name;
private int credits;
private int contactHours;
public Dummy()
{
this("", 0, 0);
}
public Dummy(String name, int credits, int contactHours)
{
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// More stuff here, e.g. property accessors
}

public class Test {
private String name;
private int credits;
private int contactHours;
public Test {
this( "", 0, 0);
}
public Test (String name, int credits, int contactHours) {
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// more code here
}

public class Bibabu{
private String name;
private int credits;
private int contactHours;
public Bibabu(){
name = ""; // you could also write this.name and so on...
credits = 0;
contactHours= 0;
}
// more code here
}

You don't need a constructor:
public class Dummy
{
private int credits = 0;
private int contactHours=0;
private String name="";
/*
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
*/
// More stuff here, e.g. property accessors
}

//constructor
public Account(int id, double balance, Person owner){
this.id = id;
this.balance = balance;
this.owner = owner;

Related

How to set a default value in class when an object is created

I want to make card number of the customer is always set to -1 when a new customer is created.
Image of how code looks likes
public Customer(int cardNumber, int yearOfBirth) {
this.cardNumber = cardNumber;
this.yearOfBirth = yearOfBirth;
}
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
This is one way to do it. Add an initializer to the field declaration.
public class Customer {
private int cardNumber = -1;
private int yearOfBirth;
public Customer(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
}
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
}
Another alternative would be to explicitly initialize the field to its default value in the constructor; e.g.
public Customer(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
this.cardNumber = -1;
}

am confused on how to do the gets and sets method

Create gets and sets methods:
getStudentName() and setstudentName()
getStudentNumber() and setStudentNumber()
I am confused on what to put in the public void printGrades() and printAverage()
import java.util.Scanner;
public class studentGrader
{
Scanner input = new Scanner(System.in);
private String studentName;
private String studentNumber;
private String[] testNames;
private int[] testGrades;
private int currentTestPointer;
private int maxTestCount = 10;
private int averageGrade;
private int testScore;
public studentGrader(String studentNameL,String studentNumberL)
{
studentName = studentNameL;
studentNumber = studentNumberL;
testNames = new String[maxTestCount];
testGrades = new int[maxTestCount];
currentTestPointer = 0;
averageGrade = 0;
}
public void addTest(String testName, int testScore)
{
testNames[currentTestPointer] = testName;
}
public void printGrades()
{
}
public void printAverage()
{
}
}
//Most Getters are very simple.
//The goal is to simply return some variable that is privately stored in a class
//Notice that the variable "studentName" is of type "String" and the method is returning a type "String"
public String getStudentName() {
return studentName;
}
//Most Setters are the same as getters, except they set the variable instead
//This method takes in a parameter(in this case "name") and then sets the desired variable to given parameter
public void setstudentName(String name) {
studentName = name;
}
The getStudentNumber and setStudentNumber are the same and I'll leave that left undone as a mental exercise.
//This is an example of how to print something
public void printAverage() {
//There may be additional logic in here to determine the correct average grade
system.out.print(averageGrade);
}
There are some rules from Java code style (that not flow to error, but they are used by everyone) along with some JVM defaults:
Class name should be in camel-case: class studentGrader - class StudentGrader
Scanner class is used to work with inbound data (console, files, ets); this is not a data holder. Should be removed from the class and used as local variable in method.
In constructor (usually), same name for local properties and method parameters should be used. To get access to the local properties, do use this: this.studentName = studentName
Arrays testNames and testGrades are objects with know size. So you should declare it in the class definition and make it final (reference is final, but not array's content): private final String[] testNames = new String[10]; and private final int[] testGrades = new int[10];
Class local parameters are initialized to the default values. For int it is a 0. So no need to do it in the constructor for currentTestPointer and averageGrade
void addTest(String testName, int testScore), in your current increment currentTestPointer and check for arrays out of bound (not more than 10) (I think, it is better to use Map)
averageGrade should be double (I think): private double averageGrade;``
Finally, your class could look like this:
public class StudentGrader {
private static final int MAX_TEST_AMOUNT = 10;
private String studentName;
private String studentNumber;
private final String[] testNames = new String[MAX_TEST_AMOUNT];
private final int[] testGrades = new int[MAX_TEST_AMOUNT];
private int currentTestPointer;
private double averageGrade;
private int testScore;
public StudentGrader(String studentName, String studentNumber) {
this.studentName = studentName;
this.studentNumber = studentNumber;
}
public void addTest(String testName, int testScore) {
if (currentTestPointer < MAX_TEST_AMOUNT) {
testNames[currentTestPointer] = testName;
testGrades[currentTestPointer] = testScore;
currentTestPointer++;
}
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public void printGrades() {
// <testName>: <testGrade>
for (int i = 0; i < currentTestPointer; i++)
System.out.println(testNames[i] + ": " + testGrades[i]);
}
public void printAverage() {
averageGrade = 0;
if (currentTestPointer > 0) {
for (int i = 0; i < currentTestPointer; i++)
averageGrade += testGrades[i];
averageGrade /= currentTestPointer;
}
System.out.println(averageGrade);
}
}

create unique id without using constructure and setters

class person {
private int id ;
private String name;
private boolean gender;
public person() {
}
public AtomicLong getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
}
I want to create unique id in this class without using constructors and setters.
To construct a person instance, the field initializer will be copied into the constructor. Assuming that's okay, you could use an AtomicInteger and something like,
private static AtomicInteger ai = new AtomicInteger(0);
private int id = ai.incrementAndGet();
you could add:
private static int ID_GENERATOR = 0;
then, in the constructor, you will use:
public person() {
id = ID_GENERATOR++;
}

Inheritance super variables

I'm writing a simple program in which I have a super class Person inherited by the sub-classes Customer and Employee (they inherit the variables ID, name and surname).
public class Person {
int id;
String name;
String surname;
public Person() {}
public Person(int i, String n, String s) {
id = i;
name = n;
surname = s;
}
}
public class Employee extends Person implements Serializable {
String username;
String password;
String date;
int hpw;
int recordSold;
float hourPay;
public Employee() {}
public Employee(String u, String n, String s, String p, int i, int h, String d, int rSold, float hPay) {
username = u;
super.name = n;
super.surname = s;
password = p;
super.id = i;
hpw = h;
date = d;
recordSold = rSold;
hourPay = hPay;
}
}
However the problem is here: when I try to get the variables ID, name and surname through my main class, they fail to return (0,null,null). Why is this? I have get-Methods in my sub-classes which should return the super variables, but they are not. Thanks for your time and patience.
public String getName() {
return super.name;
}
UPDATE:
ok so I sorted out the super(id,name,surname) in the Employee class constructor. I also removed all the getters and setters in the employee class since those are inherited from the Person superclass (correct me if I'm wrong?..)
Person superclass:
public class Person {
private int id;
private String name;
private String surname;
public Person () {
}
public Person(int i, String n, String s) {
this.id = i;
this.name = n;
this.surname = s;
}
public void setID(int i) {
this.id = i;
}
public void setName(String n) {
this.name = n;
}
public void setSurname(String s) {
this.surname = s;
}
public int getID() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
}
Employee subclass:
import java.io.*;
public class Employee extends Person implements Serializable {
protected String username;
protected String password;
protected String date;
protected int hpw;
protected int recordSold;
protected float hourPay;
public Employee() {
super();
}
public Employee(int i, String u, String n, String s, String p, int h, String d, int r, float hP) {
super(i,n,s);
username = u;
password = p;
date = d;
hpw = h;
recordSold = r;
hourPay = hP;
}
public void setUser(String u) {
username = u;
}
public void setPassword(String p) {
password = p;
}
public void setHWeek (int h) {
hpw = h;
}
public void setDate (String d) {
date = d;
}
public void setRSold (int r) {
recordSold = r;
}
public void setHPay (float p) {
hourPay = p;
}
public String getUser() {
return username;
}
public String getPassword() {
return password;
}
public int getHWeek() {
return hpw;
}
public String getDate() {
return date;
}
public int getRSold() {
return recordSold;
}
public float getHPay() {
return hourPay;
}
however, when I run the main program the ID, name and surname variables are still null, they are not being returned by the superclass. Am I missing something please? Thanks
Inheritance only works for methods NOT for variables. It is also bad practice to implement methods in subclasses that access super class variables directly. You'd better implement access methods in your superclass. Due to inheritance, those methods will be available in the sub-classes ass well.
Another thing is the visibility of you instance varibles. You are using the default visibility which is "package-wide". So if your sub-classes are not in the same package, they can't access those variables. If you use "private" or "protected" visibility you are much safer accessing the variables.
Another point is that you are initializing the objects not correctly. Calling the sub-class constructor has to call the super-class constructor as well because your Employee object relies on the functionality that your Person object provides. A more scientific description of this principle exists:
Barbara Liskov - Liskov substitution principle
public class Person {
private int id;
private String name;
private String surname;
public Person() {}
public Person(int i, String n, String s) {
id = i;
name = n;
surname = s;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public int getSurname() {
return this.surname;
}
}
Add access methods for super class instance variables and set visibility to private.
public class Employee extends Person implements Serializable {
private String username;
private String password;
private String date;
private int hpw;
private int recordSold;
private float hourPay;
public Employee() {}
public Employee(String u, String n, String s, String p, int i, int h, String d, int rSold, float hPay) {
super(id, name, surname);
this.username = u;
this.password = p;
this.hpw = h;
this.date = d;
this.recordSold = rSold;
this.hourPay = hPay;
}
}
Call the super class constructor for initialization of the super class.
Your code should look something like this:
public class Person {
private int id;
private String name;
private String surname;
public Person (int id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
public int getId() {
return id;
}
... //similarly for getName() and getSurname()
}
public class Employee extends Person {
private String username;
private String password;
private String date;
private int hpw;
private int recordSold;
private float hourPay;
public Employee (int id, String name, String surname, String username, String password, String date, int hpw, int recordSold, float hourPay) {
super(id, name, surname);
this.username = username;
... //similarly for other parameters.
}
}
The important bit is super(id, name, surname).
EDIT
lionc claims that I did not answer the question, which is true. I did this because the original poster seems to be new to Java and, hence, might be asking the "wrong" question. I should have highlighted this in my original response. Given that my answer is currently marked as the best, I believe that I made the right decision.
You haven't initialized those variables, that's why it is returning default value for those variables. In java following are default values for variables.
int -> 0
String -> null (because String is Object in Java)
You define those attributes in both of your classes so you override them in the subclass. Moreover, your Employee constructor is not the way it should. You should call the adapted super-constructor as your first statement.
public class Person {
protected int id;
protected String name;
protected String surname;
public Person(int id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
}
public class Employee extends Person implements Serializable {
private String username;
private String password;
private String date;
private int hpw;
private int recordSold;
private float hourPay;
public Employee(String username, String name, String surname, String pswd, int id,
int hpw, String date, int rSold, float hPay) {
super(id,name,surname);
this.username = username;
this.password = pswd;
this.hpw = hpw;
this.date = date;
this.recordSold = rSold;
this.hourPay = hPay;
}
}
In your constructors, I consider a best practice to give the same name to your parameters as the name of your attributes to initialize and differenciate them thanks to this. Some people also use the same names except that they add a _ at the beginning of all the members of the class. In any case, don't use such meaningless names as "s", "n" etc when the variables they represent have a special meaning (surname, name). Keep those names for example for local variables without any particular semantic (n would be an integer, s would be a String...).
In your example, you don't need tu use super to access the attributes defined in the super class since you are using package visibility for them (and both seems to be in the same package).
However, this is NOT the proper way to write Java code.
You should define a visibility for your attributes. In most case, it is recommended to use private visibility and to define getter and setter methods to access them:
public class Person {
private int id;
private String name;
private String surname;
public Person() {}
public Person(int id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
// And so on...
}
In sub-classes, you just have to call getId() or setId(...) to access the Id attribute. No need to call super.getId(). Since Employee extends Person, it has access to all of its public, protected (and package if they are in the same package) attributes and method.
This means that in your current code, you can simply write name = n instead of super.name = n.
public class Employee extends Person implements Serializable {
private String username;
private String password;
private String date;
private int hpw;
private int recordSold;
private float hourPay;
public Employee() {}
public Employee(String username, String name, String surname, String password, int id, int hpw, String date, int rSold, float hPay) {
super(id, name, surname);
this.username = username;
this.password = password;
this.hpw = hpw;
this.date = date;
this.recordSold = rSold;
this.hourPay = hPay;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
// And so on...
}
Now to use these classes, you can write code like:
Employee e = new Employee("user3149152", "Ulrich", "Ser", "passwd", 1234, 0, "2014/08/13", 0, 0);
System.out.println("Employee " + e.getName() + ' ' + e.getSurname() + " has for id " + e.getId() + '.');
For reference, this code works even with your current code.
It prints:
Employee Ulrich Ser has for id 1234.

Create unique incremental id and add it to the set

The problem is that I need to create new incremental ID for each new customer and add it to the Set, I'm trying to do it with the while loop, but it seems not to be right
public class Bank {
private String name;
private Set<Customer> customers = new HashSet<Customer>();
private Set<AbstractAccount> accounts = new HashSet<AbstractAccount>();
private Integer lastCustomerId = 0;
private Integer lastAccountId = 0;
public Integer addCustomer(String firstName, String lastName) {
// generate id from lastCustomerId and increment it
// add to Set
return lastCustomerId++;
}
public Integer addAccount(Integer ownerId, AccountType type) {
// add to Set
}
}
Im not sure if is that what you want...
public class Bank
{
private String name;
private Set<Customer> customers = new HashSet<Customer>();
private Set<AbstractAccount> accounts = new HashSet<AbstractAccount>();
private static int lastCustomerId = 0;
private static int lastAccountId = 0;
public static int GetNextCustomerID()
{
lastCustomerId++;
return lastCustomerId;
}
public static int GetNextAccountID()
{
lastAccountId++;
return lastAccountId;
}
public int addCustomer(String firstName, String lastName)
{
// generate id from lastCustomerId and increment it
int customerId = GetNextCustomerID();
// add to Set
}
public int addAccount(int ownerId, AccountType type)
{
// add to Set
int accountId = GetNextAccountID();
}
}

Categories

Resources