append a method inside a list in JAVA - java

i am a begginer with Java but i want to ask if i can append a method inside a list and how can i make a list? here is my code
public class My_Zoo {
private String Animal_name;
private String Cohabitation;
private String Gender;
private int Weight;
private int Maximum_age;
private String Animal_code;
public void Get_Animal(String A_name, String C, String G , int W , int M_a, String A_c ){
Animal_name = A_name;
Cohabitation = C;
Gender = G;
Weight = W;
Maximum_age = M_a;
Animal_code = A_c;
}
public void Tiger(){
Animal_name = "Tiger";
Cohabitation = "mammal";
Gender = "Female";
Weight = 170;
Maximum_age = 15;
Animal_code = "A01";
}
}

As you are starting with Java I think there are some things that we might say.
Java Conventions
In Java the name of everything has a convention, you can find it here:code conventions
Let me say some that might help you:
Class names: you do not use undescore, you will allways use CamelCase with first letter in capital, for exemple insteade of My_Zoo you should use MyZoo
Variable and parameters name: same as above, but withou first letter in capital, instead of Animal_name you should use animalName
Constructors
I noticed that you tried to make 2 constructors, Get_Animal and Tiger. In java all constructors have the same name of the class. If you do not put any constructors inside a class Java will use the default constructor that looks like this.
public MyZoo(){}
The only difference allowed between constructors is it´s parameters, so you cannot create it with different names, but you can make static methods that create objects for you:
public static MyZoo Tiger(){
MyZoo tiger = new MyZoo();//create the object
//use this to set the fields you you want
return tiger; //return the desired object
}
You can make the methods getAnimal and Tiger to be this way.
More information about static methods: static methods
Lists
In Java we have a class called Collections, on java.util package. All forms of collections extends from it, including the List class.
Those classes has methods to abstracts arrays and matrices processes. More about it: Collections
As it means only to hold a set of values your question doesn´t make sense, it seems that you are asking how to put a method inside a class. To me it appears you are mistaking list with class concept.
Although with java 8 or +, you can use the functional interface an make use of the function as a high order cientizen concept and add methods to a list, that must be a list of methods from the begning, as you are starting in Java and it is a advanced concept I don´t think it is your doubt.
Methods
At least let´s go to your question, but you already made it. Methods in java has 3 basic components: access modifier, return type and a name. You made 2: Get_Animal and Tiger. In Java syntax they are methods, not constructors as I said earlier. If you want put more methods just follow these rules, it´s pretty simple: Java Methods
I hope that things got more clear for you.
And you should learn more about Object Oriented concepts as weel, for example encapisulation, so you can access your fields from outside this class, you noted them with private modifier, so outside your class no one can see them.

Related

Abbreviated form of Java getter/setter field methods

Im curious if there exists an abbreviation form for getter/setter methods of objects
SimpleObject oSimple = new SimpleObject();
oSimple.setCounterValue(oSimple.getCounterValue() + 1);
like one for simple datatypes
int counter = 0;
counter += 2;
Info
The getter/setter methods are required.
Addition
If there isn't a language feature thats support the idea, what is the most convenient way to deal with that in context of good and clean code?
You have C# background I can imagine ;-)
It's not possible in Java (apart from not-quite-the-same solutions such as having public properties etc). Same as operator overloading, which could also have solved your issue.
However have a look at http://www.eclipse.org/xtend/ though, it's a JVM language similar to Java that supports operator overloading and some other nifty things.
As geert3 said there is no shortcut to setters/getters in Java without accessing the property directly.
In your case your SimpleObject-class should just have a method increaseCounter() and maybe increaseCounterBy(int add) (or simply add(int a)).
For this case, I create annotation
/**
* Annotation for PropertiesContainer class (that has field without getter and setter)
* This class look like as class with Properties in C#
*
*/
public #interface PropertiesContainer {
}
Add add to any class (annotation shows that isn't error)
#PropertiesContainer // class without getter and setter
public Class SomeObject{
public int counter;
}
And just use:
oSimple.counter++;
If the value doesn't have to be checked for any wrong values / execute code when setting it, you could solve it by just referencing the variable directly:
public Class SomeObject{
public int value;
}
public Class Main{
public static void main(String[] args){
SomeObject o = new SomeObject();
o.value += 1;
}
}
If the example you gave is all you want to do (increment and assign an index for a new object every time you make one) then a common practice is use a static variable as a counter and a local variable for the specific index.
class SomeObject {
static int objectCounter;
private int index;
public SomeObject() {
index = objectCounter++;
// additional constructor code
}
}
If you wish to add a number to a variable, I'd consider making a separate method that does just that rather than trying to rewrite set(), or if it makes sense, make it part of the code for the set().

java.lang.object cannot be converted to (selfmade class)

I'm new to java, just about to finish programming fundamentals at uni, so I'd appreciate thorough explanation of any answers. Thanks. Also by the way I am using BlueJ as part of my university training so that might be relevant.
Anyway, here's the problem; I made a text adventure for one of my assignments, and it was very procedural designed, so I decided to revamp it afterwards into a more object oriented program. I think all you need to know about are 4 class'
(some unimportant bits are left out otherwise this would be pages long but if you think they are important let me know);
inventory
static room room;
public inventory(room room)
{
this.room = room;
}
public static room getRoom()
{
return room;
}
room
ArrayList <object> objects = new ArrayList <object>();
public ArrayList getobjects()
{
return objects;
}
object
ArrayList<String> names = new ArrayList<String>();
public ArrayList getNames()
{
return names;
}
textparse (textparse has a textparse method)
public static void textparse(String line)
{
if (line.indexOf(" ") != -1){
int space = line.indexOf(" ");
noun = line.substring(space + 1, line.length()).toLowerCase();
verb = line.substring(0, space).toLowerCase();
}
else
verb = line;
verbparse();
}
Here's the problem; room has an arraylist of objects which are present in it, object has an arraylist of names they can be called by the player. This is my code to attempt to check whether the noun recognized earlier by the textparse class matches any of the objects' names. This is in the textparse class by the way;
public static object nounparse()
{
for (int counter = 0; counter < inventory.getRoom().getobjects().size(); counter++)
{
object current = inventory.getRoom().getobjects().get(counter);
if (current.getNames().contains(noun)){
return current;
}
}
return null;
}
It returns the error 'incompatible types:java.lang.Object cannot be converted to object' referencing this line
object current = inventory.getRoom().getobjects().get(counter);
I'm not sure why it thinks that the output of this is an Object, but due to my limited experience in the field I'm not even sure what an Object is besides a general classifier of a instance of a class. Any help would be appreciated. Thanks!
You are missing a generic parameter. Your getRooms() should return ArrayList<object>, if that's your desired behavior.
Also, you should really rename your object into something else, like Thing and Item, or it may cause confusion, typo, wrong reads (i.e. you may later think you wrote Object not object), etc. All class names are also recommended to be written in Big Camel Case.
Further readings
Java Generics: Java Generics Tutorial at Oracle.com
Java naming convention: (too lazy to find one, see the answer of #DanielWiddis)
The specific source of your error is a downcast. The return type of inventory.getRoom().getobjects().get(counter) appears to be ArrayList. An ArrayList is of type Object in Java, but your lowercase object appears to be a new class definition that is not a superclass or interface for ArrayList. You could refer to it as an ArrayList or List or Collection or Object (note the capitalization), but you are trying to assign it the type object.
For more information on using superclass types, search for tutorials on Java inheritance.
If your object type really was compatible with the ArrayList you could type cast it to the object type, like:
object current = (object) inventory.getRoom().getobjects().get(counter);
However, I seriously doubt that will work in this case and is almost certainly not what you intend; don't play with typecasting unless you know what you're doing. :) I only offer this for you to do more research on typecasting to understand it better.
Also, you need to take a quick look at java coding conventions regarding capitalization of class names and use of camelCase for variable and method names; it'll make your code more readable.

what is the use of a parameterized constructor in java?

Im a beginner in java and i wanted to know in a simple way why you should use a parameterized constructor instead of a default one provided by the compiler.
Thanks
You'd need to use parameterized objects anytime you want to pass any sort of configuration into your object. You could use setters to pass in that information later, but not only is it shorter and cleaner to pass that information in at construction time, it lines up with the good practice of creating immutable objects, which cannot be modified after construction and have no setters. For example,
class Student {
private final String name;
private final Date birthday;
public Student(String name, Date birthday) {
this.name = name;
this.birthday = birthday;
}
}
In Java, a constructor is a method which is called by Java runtime during the object creation using the new operator. A reason for creating a constructor could be:
To initialize your object with default or initial state since default values may not be what you are looking for. For example, if you have a person class, containing a name and date of birth, you want these fields to be filled, not empty. So you would pass the values of the name and date of birth into the constructor of that class to assign the object with a value to use in that class.
By the default constructor any attributes your object might have are set to 0, false et cetera. If you want to set the attributes right away you can use a parameterized constructor. Also using you own constructor of course gives you the option of executing code before the object (technically while) is created.
By the way: The answer that "the default won't set any value to the properties" is wrong. For example this code:
public class Test {
private int test;
private boolean test2;
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.test);
System.out.println(test.test2);
}
}
Will print out "0" and "false".
As in any object oriented language, a constructor method is used to allocate and initialize the memory for an object. With this in mind, a parameterized constructor method is used for setting properties of the object to certain value, while the default won't set any value to any of the properties.
In addition to what Louis Wasserman said, there are many situations where paramaterizing constructors makes sense from a logical point of view. Say you want to make an Employee object. There are certain attributes an employee MUST have to even be considered an employee, like a name, social security number, company and ofcourse a salary (slavery is illegal). Therefore, it would be logical to make a parameterized constructor requiring the 4 aforementioned variables.
Constructor helps class to initialize and set values to there some properties that are passed to it.That may be for current object of class.
For Ex.
class Education{
String typeOfEducation; //values are not set
String courseName;
Education(String type,String name){
typeOfEducation=type;
courseName=name; //values are set
}
}
Hope this helps.
I'm surprised no one has brought up overloading in this thread. Parameterized constructors also give the user the ability to set up an object to varying degrees based on information you have at creation time. You can do this with method overloading.
For example:
public Car(long vin){
this.vin = vin;
}
would set up a car object with only a vin number whereas this:
public Car(long vin, String make){
this.vin = vin;
this.make = make;
}
would create a similar Car object with additional information. In addition to overloading, you ought to look into copy constructors as well to get an idea of 'shallow' vs. 'deep' object copies. The following link has a decent example: http://www.geeksforgeeks.org/copy-constructor-in-java/

Is there any purpose to make private class variable to public

Hello I am curious to know that Is there any purpose to make private class variable to public in Java.
public class XYZ {
public String ID;
public ABC abc;
private class ABC {
public boolean isExist;
}
}
Thanks in advance.
Yes, there's a purpose. If you do that then those program elements which can access the class can manipulate that variable directly. Otherwise (say if the variable is private), those elements would still be able to access the class but won't be able to manipulate the variable (unless you provide a getter/setter for it).
Think about it this way: the class modifier defines the level of access to the class, the variable modifier then defines the level of access to the variable itself (for those elements which can access the class).
This is sometimes done for data-only classes. For example, this is sometimes done to represent the models stored in databases (see Objectify for a real example of how this is used, in conjunction with annotations, to represent the database models that are stored in an App Engine database).
That being said, this sort of thing makes for a very poor API. If you do this, I'd suggest doing it with classes that are either package-level access or in private nested classes, only. When exposing functionality or data to code outside your package, it is generally better to do it with a carefully designed interface that would allow you to change the implementation if your underlying structure were to change.
That is to make isExist visible to XYZ class.
Note, ABC is only visible to XYZ and not to any outside classes and its variable is public so you can have access to it. private has not meaning to XYZ, only outside classes
From inside XYZ,
ABC abc = new ABC(); //can only be accessed by XYZ.
abc.isExists = true; //can only be accessed by XYZ
Making isExist public means you do not care about encapsulating (prevent it from unwanted manipulation from outside) it. If you make it private, you will need a get accessor to expose it
private class ABC {
private boolean _isExist; //only through accessors
public boolean isExist()
{
return _isExist;
}
}
You can do either of the following two things to your class instance variables:
THING # 1: Keep your instance variables private. Then have public getter and setter methods to get and set the value of that variable. The good thing about it is that you get to put checks inside the setter method. For example, lengths can never be negative. So, you can't just make lengths public and let anyone assign it whatever value they want. You need to make sure the value being assigned to it is not negative. So:
class myClass {
private int length;
public void setLength(int i) {
if ( i > 0 ) {
length = i;
}
}
}
Also, you can make your instance variables read-only, write-only, or read-and-write, depending on the availability of getter and setter methods for that private variable.
THING # 2 : If you don't need any restrictions on the value of your instance variable, and you want it to neither be read-only nor write-only, then it's fine to keep that variable public. For example: babies can have any name - no restrictions:
class Baby {
public name;
}
class Mother {
public void nameTheBaby() {
Baby baby = new Baby();
baby.name = "Sarah";
}
}

Extending String for Typesafety - Java

I am considering a design in Java where I want a string object but with more 'type-safety' than just being of class String. This because I have a number of 'POJO' objects for Hibernate, representing my database tables. Each of these classes has a large number of public static fields representing the properties of the class, I.e.:
public class PersistantBean {
public static String PROP_FIELD_COLUMN_ONE="columnOne";
public static String PROP_FIELD_COLUMN_TWO="columnTwo";
// [...]
These properties are used when we need to access a property in a generic way, e.g. for code I am currently writing .parseAndSet(PROP_FIELD_PRICE,"£3.00").
I would like to be able to add a stronger type to the PROP_FIELD_... fields so that I could write
public class PersistantBean {
public static PropertyName PROP_FIELD_COLUMN_ONE="columnOne";
public static PropertyName PROP_FIELD_COLUMN_TWO="columnTwo";
// [...]
with minimal changes to other parts of the project,
so that parseAndSet would look like:
public void parseAndSet(PropertyName prop, String priceToParse)
Essentially, I would like PropertyName to be a type that is like String in everyway apart from the compiler would error if I tried to put a String where a PropertyName was expected, is any design pattern like this possible.
(I am shying away from Enums, although now I mention it, Enums may be the way to go.)
For Java 1.5 and above, just use an enum type.
For Java 1.4 and below, use the typesafe enum pattern. E.g.
public class Suit {
private final String name;
public static final Suit CLUBS =new Suit("clubs");
public static final Suit DIAMONDS =new Suit("diamonds");
public static final Suit HEARTS =new Suit("hearts");
public static final Suit SPADES =new Suit("spades");
private Suit(String name){
this.name =name;
}
public String toString(){
return name;
}
}
enum(enumeration) is a better idea, which above mentioned scenario.
eg:
enum PROP_FIELD_COLUMN {
columnOne, columnTwo,etc
}
I'd use an Enum. That way you get compile-time checking.
If your Strings really have a good fairly standard naming convention, like "column" + "One", "Two", etc. as in your example, you could save a lot of work by combining an enum for the prefix with an int for the suffix. So, create a class or utility method that takes an enum for the prefix, e.g. COLUMN, and combines it with an int, say 2, to yield "columnTwo".
An alternative might be be for your code, like parseAndSet, to validate the passed in String against an array or Collection of legal Strings, or maybe a regex, and throw an IllegalArgumentException. You'd get runtime checking and if you have good unit tests this could work.
EDIT ADDED
#sethupathi.t had a nice idea in his answer - In some cases it may be preferable to make the 2nd argument (for which I used an int) also an enum.
As far as I can tell, there are two reasonable ways to do what you want to do.
The first way (and probably best way, if it works for you) is to use an enum, as mentioned in another answer.
The second way, which may be necessary if you do not know all of your PropertyName's at runtime, would be to use a PropertyNameFactory along the lines of:
public class PropertyNameFactory
{
public static PropertyName getPropertyName(String propertyName)
{
// Check validity of the propertyName against what ever rules we
// have defined (maybe valid propertyNames are read from a DB at
// startup, etc).
if (isValid(propertyName))
{
// Ideally get from a cache, but for the sake of the example
// we will create a new one...
return new PropertyName(propertyName);
}
throw new IllegalArgumentException("Invalid property name: " + propertyName);
}
}
This is not ideal in that it does not provide true type safety of your property names, but it does ensure their validity.
I have to second the Enum answers.
However, a more literal answer to your question is that Java provides an interface for String-like objects, java.lang.CharSequence, and many parts of the standard Java libraries have been updated to accept CharSequence where appropriate. This will not however give you the behavior that you want, which is to have your class behave as a subtype of String.

Categories

Resources