define constructors in java - java

I am working on a java code to create a class Students and I should define two constructors and one has to be with parameters and one without parameters I have already done the one with parameters but I am having a problem understanding how to do the one without parameters This is what I have to do:
setStudent()that takes three parameters: a string name, an integer grade, and a double cgpa value.
It stores these parameters into the three member variables of the class.
getNamethat returns the value stored in the member variable name.
getGradethat returns the value stored in the member variable grade.
getCGPAthat returns the value stored in the member variable cgpa.
printStudent that displays the values of the three member variables.
I have done most but I do not know what to do with the last thing printStudent.
My class :
public class Students{
private String Name;
private int Grade;
private double CGPA;
public Students(String Name, int Grade, double CGPA){
this.Name = Name;
this.Grade = Grade;
this.CGPA = CGPA;
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public int getGrade(){
return Grade;
}
public void setGrade(int Grade){
this.Grade = Grade;
}
public double getCGPA(){
return CGPA;
}
public void setCGPA(double CGPA){
this.CGPA = CGPA;
}
}
and that is my main :
public class LAB4EX1{
public static void main(String [] args){
Students student1 = new Students("Nasser", 90, 3.4);
Students student2 = new Students("Adnan", 92, 3.72);
Students student3 = new Students("Mohammed", 91, 3.5);
}
}
I need to make it print the output for me.
Any help would be really appreciated.

You have do declare a constructor without any parameters and override toString method:
public class Students{
private String Name;
private int Grade;
private double CGPA;
public Students(String Name, int Grade, double CGPA){
this.Name = Name;
this.Grade = Grade;
this.CGPA = CGPA;
}
public Students(){ // empty constructor
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public int getGrade(){
return Grade;
}
public void setGrade(int Grade){
this.Grade = Grade;
}
public double getCGPA(){
return CGPA;
}
public void setCGPA(double CGPA){
this.CGPA = CGPA;
}
#Override
public String toString() {
return "Students{" +
"Name='" + Name + '\'' +
", Grade=" + Grade +
", CGPA=" + CGPA +
'}';
} // toString() for printing your three fields
}

Related

Encapsulation (User Input)

//this is my main class
import java.io.*;
import java.util.*;
public class TheInnovator{
private String name;
private String age;
private String designation;
private String course;
private String yrlvl;
public TheInnovator(String name, String age, String designation, String course, String yrlvl){
this.name = name;
this.age = age;
this.designation = designation;
this.course = course;
this.yrlvl = yrlvl;
}
public void setName(String name){
this.name = name;
}
public void setAge(String age){
this.age = age;
}
public void setDesignation (String designation){
this.designation = designation;
}
public void setCourse(String couse){
this.course = course;
}
public void setYrlvl (String yrlvl){
this.yrlvl = yrlvl;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
public String getDesignation(){
return designation;
}
public String getCourse(){
return course;
}
public String getYrlvl(){
return yrlvl;
}
}
// this is my Main Driver
import java.util.*;
public class MainDriver{
public static void main(String args[]){
TheInnovator theinnov = new TheInnovator();
Scanner input = new Scanner(System.in);
theinnov.setName = (input.nextLine());
theinnov.setAge = (input.nextLine());
theinnov.setDesignation = (input.nextLine());
theinnov.setCourse = (input.nextLine());
theinnov.setYrlvl = (input.nextLine());
System.out.println("Name: " + theinnov.getName());
System.out.println("\nAge: " + theinnov.getAge());
System.out.println("\nDesignation: " + theinnov.getDesignation());
System.out.println("\nCourse: " + theinnov.getCourse());
System.out.println("\nYear Level: " + theinnov.getYrlvl());
}
}
So my problem is everytime I run the MainDriver.java, it cannot find my setter variables. what's wrong or what's missing in my code? thank you for a quik response! anyway I'm using notepad++ on this because it's a requirement.
You need to remove the = sign. It makes the compiler think that setName is a field and not a method.
theinnov.setName (input.nextLine());
class Quick {
public static void main(String[]args) {
Don op=new Don();
Scanner sc=new Scanner(System.in);
System.out.println("enter");
op.setName(sc.nextLine());
System.out.println("Name: " + op.getName());
}
}
class Don
{
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName(){
return name;
}
}
Output: Name: loyal

Removing Duplicate Objects that contain different variables

I have two objects that have the same name but contain different ages(values), I tried adding these objects to a map to remove duplicates but it won't remove. This is the model code I am testing:
two ab = new two("john", "20");
two ac = new two("chan", "30");
two ad = new two("john", "34");
ArrayList<two> ae = new ArrayList<>();
public void adding(){
ae.add(ab);
ae.add(ac);
ae.add(ad);
System.out.println(ae);
}
public void removeDuplicate(){
Set<two> lhs = new HashSet<>();
lhs.addAll(ae);
ae.clear();
ae.addAll(lhs);
System.out.println(ae);
}
public static void main(String args[]){
one five = new one();
five.adding();
five.removeDuplicate();
}
This is the class that is used for object type:
package teeestserrr;
public class two {
private String name;
private String age;
public two(String name, String age){
this.age = age;
this.name = name;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
public String toString(){
return name + " " + age;
}
}
Results are :
[john, chan, john]
[chan, john, john]
I also tried to make the toString return only name but the map used to remove duplicates doesn't seem to work even in that case. I don't understand and I cannot identify the underlying problem. Any help is appreciated.
You have to override equals and hashcode method in two.
Equals should give result according to only name field and also hashcode should be formed using only name field, that will help you to achieve your aim.
package teeestserrr;
public class two {
private String name;
private String age;
public two(String name, String age){
this.age = age;
this.name = name;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
public String toString(){
return name + " " + age;
}
#Override
public boolean equals(Object obj){
if(obj==null)
return false;
if(name==null){
return false;
}
if(!(obj instanceof two)){
return false;
}
two another = (two)obj;
return this.name.equals(another.name);
}
public int hashCode(){
return name==null?0:name.hashCode();
}
}

Constructor + Inheritance support

I am fairly new to Inheritance, and I'm not sure if I am doing it right but I seem to be on the right track. The program runs fine except the output I am getting isn't right. I think the problem is to do with my constructors.
public class Person {
protected static String name;
protected static int birthYear;
public Person(String name, int birthYear) {
}
public String name (String n) {
n = name;
return n;
}
public int birthYear (int bY) {
bY = birthYear;
return bY;
}
#Override
public String toString() {
return String.format(name + birthYear);
}
}
public class Student extends Person {
protected String major;
public Student(String name, int birthYear, String major) {
super(name, birthYear);
major = "";
}
public String major(String maj) {
maj = major;
return maj;
}
public String toString() {
super.toString();
return super.toString() + major;
}
}
public class Instructor extends Person {
protected static int salary;
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
salary = 0;
}
public int salary(int sal) {
sal = salary;
return sal;
}
public String toString() {
super.toString();
return super.toString() + salary;
}
}
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Perry", 1959);
Student s = new Student("Sylvia", 1979, "Computer Science");
Instructor e = new Instructor("Edgar", 1969, 65000);
System.out.println(p);
System.out.println("Expected: Person[name=Perry,birthYear=1959]");
System.out.println(s);
System.out.println("Expected:" +
"Student[super=Person[name=Sylvia,birthYear=1979],major=Computer]");
System.out.println(e);
System.out.println("Expected:" + "Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]");
}
}
OUTPUT I AM GETTING:
null0
Expected: Person[name=Perry,birthYear=1959]
null0null
Expected: Student[super=Person[name=Sylvia,birthYear=1979],major=Computer Science]
null00
Expected: Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]
Try changing your constructor in Person to:
public Person(String name, int birthYear) {
this.name = name;
this.birthYear = birthYear;
}
Currently, the constructor has an empty body, so when you call super(name, birthYear); in the subclass constructor, nothing actually happens.
Your Student constructor also has an error. You forgot to initialize the major field.
public Student(String name, int birthYear, String major) {
super(name, birthYear);
this.major = major;
}
You have the same problem in the Instructor constructor...
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
this.salary = salary;
}
Finally, you need to take away the static keywords before the fields in Person. This is because static ensures, that there will always be one (and only one) instance of those fields per class, as opposed to one per instance, like you want it to be:
protected String name;
protected int birthYear;
Same thing for the salary field in Instructor.
n = name; this causing your problem. It must be name = n;. All your setter function contain this problem, correct them all and tell me result.

Java setters and getters

I have been struggling with setters and getters in java for quite a long time now.
For instance, if I want to write a class with some information as name, sex, age etc with appropriate set and get methods. Then in a another class I want to test my set and getters with this as a example:
personInfo = myInfo() = new Personinfo("Anna", "female", "17");
How do I do that?
I know that I can have a printout like:
public void printout() {
System.out.printf("Your name is: " + getName() +
" and you are a " + getSex());
}
This is a simple example to show you how to do it:
public class Person {
private String name;
private String gender;
private int age;
Person(String name, String gender, int age){
this.name = name;
this.gender = gender;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setGender(String gender){
this.gender = gender;
}
public void setAge(int age){
this.age = age;
}
public String getName(){
return this.name;
}
public String getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
public static void main(String[] args)
{
Person me = new Person("MyName","male",20);
System.out.println("My name is:" + me.getName());
me.setName("OtherName");
System.out.println("My name is:" + me.getName());
}
}
This will print out:
My name is:MyName
My name is:OtherName
Let eclipse handler it for you
Click on your variable
Source > Generate Setter / Getter
You need to create an object of one class in the other class. You can then call the .get() and .set() methods on them. I will post an example in 2 minutes
First class (i'll call it Person) will have methods to return its fields
private String name = "";
private String age = 0;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
The second class will call those methods after it creates an object of the first class
bob = new Person("Bob", 21);
System.out.println("Your name is: " + bob.getName() +
" and you are " + bob.getAge());
The point of getters and setters is to let you limit/expand the scope or functionality of your property, independent of each other.
You may want your 'name' property to be readonly outside of your PersonInfo class. In this case, you have a getter, but no setter. You can pass in the value for the readonly properties through the constructor, and retrieve that value through a getter:
public class PersonInfo
{
//Your constructor - this can take the initial values for your properties
public PersonInfo(String Name)
{
this.name = Name;
}
//Your base property that the getters and setters use to
private String name;
//The getter - it's just a regular method that returns the private property
public String getName()
{
return name;
}
}
We can use getName() to get the value of 'name' outside of this class instance, but since the name property is private, we can't access and set it from the outside. And because there is no setter, there's no way we can change this value either, making it readonly.
As another example, we may want to do some validation logic before modifying internal values. This can be done in the setter, and is another way getters and setters can come in handy:
public class PersonInfo
{
public PersonInfo(String Name)
{
this.setName(Name);
}
//Your setter
public void setName(String newValue)
{
if (newValue.length() > 10)
{
this.name = newValue;
}
}
Now we can only set the value of 'name' if the length of the value we want to set is greater than 10. This is just a very basic example, you'd probably want error handling in there in case someone goes jamming invalid values in your method and complains when it doesn't work.
You can follow the same process for all the values you want, and add them to the constructor so you can set them initially. As for actually using this pattern, you can do something like the following to see it in action:
public static void main(String[] args)
{
PersonInfo myInfo = new PersonInfo("Slippery Sid",97,"male-ish");
var name = myInfo.getName();
System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
myInfo.setName("Andy Schmuck");
System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
}
You create an object by instantiating the constructor as follows
Personinfo pi = new Personinfo("Anna", "female", "17");
You can then call methods upon that object as follows
pi.setName("Alan");
or
pi.getName();
here's how you do it:
public class PersonInfo {
private String name;
private String sex;
private int age;
/** GETTERS **/
public String getName(){
return name;
}
public String getSex(){
return sex;
}
public int getAge(){
return age;
}
/** SETTERS **/
public void setName(String name){
this.name = name;
}
public void setSex(String sex){
this.sex = sex;
}
public void setAge(int age){
this.age = age;
}
}
class Test{
public static void main(String[] args){
PersonInfo pinfo = new PersonInfo();
pinfo.setName("Johny");
pinfo.setSex("male");
pinfo.setAge(23);
//now print it
System.out.println("Name: " + pinfo.getName());
System.out.println("Sex: " + pinfo.getSex());
System.out.println("Age: " + pinfo.getAge());
}
}
Or you can add this as well:
#Override
public String toString(){
return "Name: " + this.name + "\n" +
"Sex: " + this.sex + "\n" +
"Age: " + this.age;
}
and then just to a .toString
EDIT:
Add this constructor in the class to initialize the object as well:
public PersonInfo(String name, String sex, int age){
this.name = name;
this.sex = sex;
this.age = age;
}
In personInfo:
public Person(String n, int a, String s){
this.name=n;
this.age=a;
this.sex=s;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String getSex(){
return this.sex;
}
public void setName(String n){
this.name = n;
}
public void setAge(int a){
this.age = a;
}
public void setSex(String s){
this.sex = s;
}
Then fix the print statement:
System.out.println("Your name is: " + myInfo.getName() + " and you are a " + myInfo.getSex());

constructor error

I was told that when creating a new object, it needs to have the same parameters as its constructor. Ive tried, but i still get these error. cannot find symbol s1.getCourse s1.getName s1.getAge. and also an invalid constructor error. heres my code
public class Person{
private String name;
private int age;
public Person(String name, int age){
this.name=name;
this.age=age;
}
public String getDetails(){
return "Name: " + name + "Age: " + age;
}
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public class Student extends Person{
private String course;
public Student(String name, int age,String course){
super(name,age);
this.course = course;
}
public String getDetails(){
return super.getDetails()+"Course: "+ course;
}
public void setCourse(String course){
this.course=course;
}
public String getCourse(){
return course;
}
public String getName(){
return name;
}
}
public String getAge(){
return age;
}
}
TestPerson
student++;
String name=array[0];
int age=Integer.parseInt(array[1]);
String course=array[3];
Student s1= new Student(name,age,course);
System.out.println("name "+s1.getName());
System.out.println("age "+ s1.getAge());
System.out.println("course: " + s1.getCourse());
}
}
For more Detail can u provide Person class.
You have not provided the name and age attribute in student class.
if all this is present in super class then also When u call the s1.getName() method it will call from student class. because it present in sub class i.e student

Categories

Resources