Methods with same name as its class? [duplicate] - java

This question already has answers here:
Java Constructors
(10 answers)
Closed 5 years ago.
public class Person {
private int age;
public Person(int initialAge) {
if (initialAge<= 0) {
System.out.println("Age is not valid, setting age to 0.");
}
else {
age = initialAge;
}
// Add some more code to run some checks on initialAge
}
public void amIOld() {
if (age < 13) {
System.out.print("You are young.");
}
else if (age >= 13 && age < 18) {
System.out.print("You are a teenager.");
}
else {
System.out.print("You are old.");
}
// Write code determining if this person's age is old and print the correct statement:
System.out.println(/*Insert correct print statement here*/);
}
public void yearPasses() {
age += 1;
}
public static void main(String[] args {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
In the code above, when an instance of the person class is created with a parameter, does it automatically call the Person method within the class?
is the code
Person p = new Person(age);
a constructor or a method call? is it both?
What is the purpose of having a method with the same name as the class?
How does it function?

I, personally, do not like a method with the same nam as the class it is in, but:
public class Person {
public Person() {} // constructor
public void Person {} // method
public static void main(String... args) {
Person p = new Person();
p.Person();
}
}
Generally, a class's name should be a noun, while a method's name should be a verb.

That's called the constructor. It's axecuted when you create a new instance like this: Person me = new Person(99);
You can have multiple constructors like:
enter code here
public Person(int initialAge) {
if (initialAge<= 0) {
System.out.println("Age is not valid, setting age to 0.");
}
else {
age = initialAge;
}
}
public Person() {
age = 0;
}
in the same class. In that case if you create an instance like this: like this: Person me = new Person(99); only the first constructor is called and if you create an instance like this: Person me = new Person(); only the second one (unless you have one referencing the other of course).

A mehtode named like the class and without void or any returntyp is called a constructor.
class MyClass {
public MyClass () {
//constructor code here
}
}
Every calss has a default constructor (showen above) witch does not have to be expilcitly written out to be used (generated by the compiler) but it can be overritten and overloaded for more functunallity.
A constructor is called everytime when an object of the class is generated.
class Person {
pulbic int age;
public Person (int age) {
this.age = age;
}
}
class Main {
public static void main(String args[]) {
//creating 2 objects of person
Person p1 = new Person(23)
Person p2 = new Person(51)
}
}
This programm now generates 2 objects of person the objct p1 holds in the age variable the value 23 and the objct p2 holds in the age variable the value 51.
The ages are set by the constructor called with the new Person(int age) statment.
If you have not initialized an class vriable (in this case int age) but set its value over a constructor, it is treated by the rest of the class as if it was initialized with a specific value.
You can force the programmer with constructors to set specific attributs of an class at its creation and can therfor be sure that this values are set.
If you overload constructors you can call another constructor with:
this(/*Overloaded parameters*/);
Constructors also can not call any methodes (exept other constructors) of the class, because the class is not fully generated a the time the constructor is running.

When an object of a class is created then
Static block is executed first
Constructor if not defined then default Constructor
After that method called with that object.
Constructor is not a method as it does not have any return type.If constructor not defined in the class then default constructor is called automatically.
Otherwise particular Constructor will be called when creating an object.

Related

Store different object type in one array and print each one with their methods

I am trying to create a parent class for cars and subclasses from it. Each one has separate methods and store them in an array then if the class are subclass try to call the method on it.
Parent class
public class car {
public String name ;
public double price ;
public car (String name , int price) {
this.name = name ;
this.price = price;
}
public String toString() {
return "car name : "+this.name
+" Price : " +this.price ;
}
}
Sub class
public class CarMotors extends car {
public float MotorsCapacity ;
public CarMotors( String name, int price , float MotorsCapacity) {
super(name, price);
this.MotorsCapacity = MotorsCapacity ;
}
public float getMotorsCapacity() {
return this.MotorsCapacity;
}
}
Main class
public class Test {
public static void main(String[] args) {
car [] cars = new car[2] ;
cars[0] = new car("M3" , 78000);
cars[1] = new CarMotors("M4" , 98000 , 3.0f);
for(int i=0 ;i<2;i++){
if(cars[i] instanceof CarMotors) {
System.out.println(cars[i].getMotorsCapacity()); // error here
}else {
System.out.println(cars[i].toString());
}
}
}
}
As you can see, I can't print the getMotorsCapacity(). I am new to Java. I think there is a cast that need to happen, but I don't now how.
Being short... a class only can see what its yours behaviors.
In your example CarMotors is a Car, that's fine.
But the behavior getMotorsCapacity() is created in CarMotors and it wasn't in Car.
That error occurs because, it's OK in a variable Car you are able to put an instance of CarMotors because CarMotors is a Car. So, any method that is in Car is also in CarMotors, yes, you can call. Look at cars[i].toString() there's no problem here.
You need explicitly say to compiler:
"- oh, right, originally this variable is a Car, but I know that is a CarMotors inside that. I will make a cast here, OK compiler? Thanks."
System.out.println(((CarMotors) cars[i]).getMotorsCapacity());
Or, to be more clear:
CarMotors carMotors = ((CarMotors) cars[i]);
System.out.println(carMotors.getMotorsCapacity());

Printing address instead of array elements? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
So in my code, I made a class named Pet, that would have both a default constructor and a non-default constructor that passes in String name, and int age of the pet.
public class Pet
{
// instance variables
private int age;
private String name;
/**
* Constructor for objects of class Pet
*/
public Pet()
{
// initialise instance variables
age = 0;
name = "somePet";
}
public Pet(int age, String name)
{
this.age = age;
this.name = name;
}
}
Then I created a class named petArray that would add to the array and print out the array...
public class PetArray
{
// instance variables
private Pet [] petArray;
/**
* Constructor for objects of class PetArray
*/
public PetArray()
{
// initialise instance variables
petArray = new Pet[5];
}
public void addPets()
{
// put your code here
Pet myPet = new Pet(4, "Spots");
petArray[0] = (myPet);
petArray[1] = new Pet(2, "Lucky");
petArray[2] = new Pet(7, "Joe");
}
public void printPets()
{
for (int i = 0; i < petArray.length; i++)
{
System.out.println(petArray[i]);
}
}
}
But then, I get this in the terminal window when trying to print it out...
Pet#13255e3c
Pet#171ac880
Pet#52185407
null
null
You forgot to override toString() method inherited from Object.
In this case you can use something like this:
#Override
public String toString() {
return (name + age);
}
Java compiler just does not know how to print it, you have to inform it :)
In your addPets() method you are only adding 3 objects to your petArray while there are 2 more spaces you need to fill as you declared that array to be a length of 5.
You could change the length of your array down to 3 or you could add 2 more objects, that should fix your problem.
And as stated above, adding the toString method will get rid of the addressing issues.
class Pet {
...
#Override
public String toString(){
// the string passed from here will be shown in console
}
}
Your output is fine according to your code. You have to override toString() method to print as per your requirement. Add this may be it will help.
#override
public string toString(){
return "your required string"; // i.e : name or name+age
}

How do I create an object from another class (BlueJ)

I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.

Actual and formal argument lists differ in length

I am making a constructor for UCSDStudent, and I found my constructor has no problems.
Please point out some specific problems and help me to make my own resolution!
class UCSDStudent extends Base {
private String name;
private long Studentnum;
public UCSDStudent (String name, long number) {
UCSDStudent s = new UCSDStudent();
s.setName(name);
s.setStudentNum(number);
}
public void setName(String setName) {
name = setName;
}
public void setStudentNum(long setStudentNum){
Studentnum = setStudentNum;
}
public String getName () {
return this.name;
}
public long getStudentNum () {
return this.Studentnum;
}
....... // some more code, but I will put the instantiation in the main func.
// create Student and place in symbol table
if(!symtab.insert (
new UCSDStudent (buffer, number), 1)){
System.out.println("Couldn't insert " + "student!!!");
}
......
UCSDStudent stu = new UCSDStudent (buffer, 0);
This is Base class.
public abstract class Base {
public String getName () { // identifier function
return null;
}
}
The statement
public UCSDStudent (String name, long number) {
UCSDStudent s = new UCSDStudent();
s.setName(name);
s.setStudentNum(number);
}
should be changed to
public UCSDStudent(String name, long number) {
this.setName(name);
this.setStudentNum(number);
}
There is no reason to create a new UCSDStudent object inside the class constructor. It will actually be lost after the constructor is executed and the values passed to the constructor will never be saved.
Also, you should take into account the Base superclass. If it needs any initialization, you should call its constructor from the first line of the UCSDStudent constructor.
public UCSDStudent (String name, long number)
{
UCSDStudent s = new UCSDStudent();
s.setName(name);
s.setStudentNum(number);
}
This code cannot possibly compile since you are calling the default constructor of UCSDStudent, which you haven't defined. You must define a default constructor if you define a constructor that takes parameters.

Issue with "non static method cannot be referenced from a static context" error [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 9 years ago.
I am having an issue with this error, while trying to write a method that lists all names in a specific class. (error at bottom) I have tried a few things but for the life of me, cannot figure it out. Please help, thanks.
Class Cat:
public class Cat
{
// instance variables
private String name;
private int yearOfBirth;
private int weightInKilos;
public Cat() {
setName("");
setYearOfBirth(0);
setWeightInKilos(0);
}
/**
*
*/
public Cat(String newName, int newYearOfBirth, int newWieghtInKilos )
{
setName(newName);
setYearOfBirth(newYearOfBirth);
setWeightInKilos(newWieghtInKilos);
}
public String getName(){
return name;
}
public int getYearOfBirth(){
return yearOfBirth;
}
public int getWieghtInKilos(){
return weightInKilos;
}
public void setName(String newName){
if (newName != null ){
name = newName;
}
else{
System.out.println("Invalid Name");
}
}
public void setYearOfBirth(int newYearOfBirth){
if (yearOfBirth >= 0){
yearOfBirth = newYearOfBirth;
}
else{
System.out.println("Year Of Birth must not be negative!");
}
}
public void setWeightInKilos(int newWeightInKilos){
if (weightInKilos >= 0){
weightInKilos = newWeightInKilos;
}
else{
System.out.println("Weight must not be negative!");
}
}
}
Class Cattery:
import java.util.ArrayList;
public class Cattery
{
// instance variables - replace the example below with your own
private ArrayList <Cat> cats;
private String businessName;
/**
* Constructor for objects of class Cattery
*/
public Cattery(String NewBusinessName)
{
cats = new ArrayList <Cat>();
NewBusinessName = businessName;
}
public void addCat(Cat newCat){
cats.add(newCat);
}
public void indexDisplay(int index) {
if((index >= 0) && (index <= cats.size()-1)) {
System.out.println(index);
}
else{
System.out.println("Invalid index position!");
}
}
public void removeCat(int indexremove){
if((indexremove >= 0) && (indexremove <= cats.size()-1)) {
cats.remove(indexremove);
}
else{
System.out.println("Invalid index position!");
}
}
public void displayNames(){
System.out.println("The current guests in Puss in Boots Cattery:");
for(Cat catNames : cats ){
System.out.println(Cat.getName()); //ERROR; non static method cannot be referenced from a static context..wtf
}
}
}
Please help, thanks
When you have an instance method, you need to call it on a specific instance of the class.
Here:
System.out.println(Cat.getName());
you're trying to call it on the Cat class itself. You want:
for (Cat cat : cats ) {
System.out.println(cat.getName());
}
Note that I've changed the name of the iteration variable from catNames to cat as well - because the value is just a reference to "the cat we're looking at at the moment". It's not the cat name, nor is it multiple cats (or cats names) - it's a single cat. It's very important to name variables carefully - it can help correct code to look correct, and incorrect code to look incorrect. It doesn't make sense to call getName() on a variable called catNames... (what is the name of a collection of names?) but it absolutely makes sense to call it on a variable called cat.
Another warning bell from your original code was that the body of your for loop didn't use the iteration variable - that almost always suggests that something's wrong. The fixed version does, of course.
Use:
System.out.println(catNames.getName());
getName is non static function, so you need to use it on an instance of that class, like you have in the cats list.
Cat.getName() this line means getName() should be static method in Cat class, but's not as such.
so access getName() method by instacne .
System.out.println(catNames.getName());
for (Cat cat : cats) {
System.out.println(Cat.getName());
}
Here you need to use cat, not Cat. So use
for (Cat cat : cats) {
System.out.println(cat.getName());
}

Categories