logo
down
shadow

Using getter and setter methods inside a class in my main class


Using getter and setter methods inside a class in my main class

By : Naga namrata
Date : November 21 2020, 07:01 PM
Hope that helps I have to write a program that writes a class called "Employee" that holds information about an employees name and salary. Then I need to use that information inside my main class to set the employee information then get the employee information and print it to the screen, but I have no idea how to access my information inside my "Employee" class to use in my "main" class. Here's what I have in my "Employee" class. , In your main class, instantiate Employee, and call the setters:
code :
Employee emp = new Employee();
emp.setName("Matt");
emp.setSalary(50000);
System.out.println("Name: " + emp.getName() + ", salary: " + emp.getSalary());


Share : facebook icon twitter icon
Why to use getter and setter methods to set class properties?

Why to use getter and setter methods to set class properties?


By : user3316038
Date : March 29 2020, 07:55 AM
Any of those help by using getter and setter you hide the internal implementation of your class. which means in the set method of a setter, you can run a whole algorithm to parse the input data into your internal data structure. you'll be able to later change your implementation without any impact to your users.
now if you expose your internal members as public, you can't hide them anymore, and any change you make to your class internal definition will probably break the user usage.
is it possible to fetch the data from the class created for getter-setter methods

is it possible to fetch the data from the class created for getter-setter methods


By : user3482776
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Yes we can do this.Make those functions public and you can use them using object of the corresponding class.Also you can make them static(but not recommended) and use them using class name itself.They are made for this purpose only.
Giving base class access to child-class variables without getter and setter methods

Giving base class access to child-class variables without getter and setter methods


By : Yulia Galon
Date : March 29 2020, 07:55 AM
I wish this helpful for you I did something similar to @Guffa's answer, but instead of the objects holding "Hook" wrappers for the properties, I used lambdas to get/set the properties using their original value types:
MasterClass:
code :
class MasterClass
{
    Dictionary<string, HookObj> dict = new Dictionary<string, HookObj>();

    //Data came in from an external source, see if we know what variable to assign the value to
    public void receiveData(string key, string value)
    {
        if (dict.ContainsKey(key))
            assignVal(dict[key], value);
        else
            throw new NotImplementedException(); //use NotImplementedException as placeholder until we make proper exception
    }

    //Cast the value-string to the proper type and assign it
    private void assignVal(HookObj hookobj, string value)
    {
        try
        {
            if (hookobj.theType == typeof(string))
                hookobj.SetValue(value);
            else if (hookobj.theType == typeof(int))
                hookobj.SetValue(Int32.Parse(value));
            else if (hookobj.theType == typeof(float))
                hookobj.SetValue(float.Parse(value));
            else
                throw new NotImplementedException();
        }
        catch (RuntimeBinderException ex) { throw new NotImplementedException("", ex); }
        catch (System.FormatException ex) { throw new NotImplementedException("", ex); }
    }

    protected void newHookAndAdd<T>(Action<T> setter, Func<T> getter, string name)
    {
        HookObj hook = new HookObj<T>(setter, getter);
        dict.Add(name, hook);
    }
}
public class HookObj<T> : HookObj
{
    public Action<T> setMethod { get; private set; }
    public Func<T> getMethod { get; private set; }

    public HookObj(Action<T> setMethod, Func<T> getMethod)
        : base(typeof(T))
    {
        this.setMethod = setMethod;
        this.getMethod = getMethod;
    }

    public override void SetValue(object value)
    {
        setMethod((T)value);
    }

    public override object GetValue()
    {
        return getMethod();
    }
}


public abstract class HookObj
{
    public Type theType { get; private set; }

    public HookObj(Type theType)
    {
        this.theType = theType;
    }

    public abstract void SetValue(object value);
    public abstract object GetValue();
}
class Attachvariable : MasterClass
{
    public int UserID { get; set; }
    public string Position { get; set; }

    public Attachvariable()
    {
        hookMethod();
    }

    protected void hookMethod()
    {   
        newHookAndAdd(value => UserID = value, () => UserID, "userID");
        newHookAndAdd(value => Position = value, () => Position, "position");
    }
}
class YesNoVariable : MasterClass
{
    public bool YesNo { get; set; }

    public YesNoVariable()
    {
        hookMethod();
    }

    protected void hookMethod()
    {   
        newHookAndAdd(value => YesNo = value, () => YesNo, "yesno", (input) => input == "yes");
    }
}
public abstract class HookObj<T> : HookObj
{
    public Action<T> setMethod { get; private set; }
    public Func<T> getMethod { get; private set; }


    protected HookObj()
        : base(typeof(T))
    {

    }

    public void SetSetter(Action<T> setMethod)
    {
        this.setMethod = setMethod;
    }

    public void SetGetter(Func<T> getMethod)
    {
        this.getMethod = getMethod;
    }

    protected abstract T Parse(string value);

    public override void SetValue(string value)
    {
        T parsedValue = Parse(value);
        setMethod(parsedValue);
    }

    public override object GetValue()
    {
        return getMethod();
    }
}


public abstract class HookObj
{
    public Type theType { get; private set; }

    public HookObj(Type theType)
    {
        this.theType = theType;
    }

    public abstract void SetValue(string value);
    public abstract object GetValue();
}
public class StringHook : HookObj<string>
{
    protected override string Parse(string value)
    {
        return value;
    }
}

public class IntHook : HookObj<int>
{
    protected override int Parse(string value)
    {
        return Int32.Parse(value);
    }
}

public class FloatHook : HookObj<float>
{
    protected override float Parse(string value)
    {
        return float.Parse(value);
    }
}
public class CustomHook<T> : HookObj<T>
{
    public Func<string, T> inputParser { get; private set; }

    public CustomHook(Func<string, T> parser)
    {
        if (parser == null)
            throw new ArgumentNullException("parser");

        this.inputParser = parser;
    }

    protected override T Parse(string value)
    {
        return inputParser(value);
    }
}
class MasterClass
{
    Dictionary<string, HookObj> dict = new Dictionary<string, HookObj>();

    //Data came in from an external source, see if we know what variable to assign the value to
    public void receiveData(string key, string value)
    {
        if (dict.ContainsKey(key))
            assignVal(dict[key], value);
        else
            throw new NotImplementedException(); //use NotImplementedException as placeholder until we make proper exception
    }

    //Cast the value-string to the proper type and assign it
    private void assignVal(HookObj hookobj, string value)
    {
        hookobj.SetValue(value);
    }

    protected void RegisterProperty<T>(Action<T> setter, Func<T> getter, string name, Func<string, T> inputParser)
    {
        var hook = new CustomHook<T>(inputParser);
        hook.SetSetter(setter);
        hook.SetGetter(getter);
        dict.Add(name, hook);
    }

    protected void RegisterProperty(Action<string> setter, Func<string> getter, string name)
    {
        var hook = new StringHook();
        hook.SetSetter(setter);
        hook.SetGetter(getter);
        dict.Add(name, hook);
    }

    protected void RegisterProperty(Action<int> setter, Func<int> getter, string name)
    {
        var hook = new IntHook();
        hook.SetSetter(setter);
        hook.SetGetter(getter);
        dict.Add(name, hook);
    }

    protected void RegisterProperty(Action<float> setter, Func<float> getter, string name)
    {
        var hook = new FloatHook();
        hook.SetSetter(setter);
        hook.SetGetter(getter);
        dict.Add(name, hook);
    }
}
class Attachvariable : MasterClass
{
    public int UserID { get; set; }
    public string Position { get; set; }
    public bool YesNo { get; set; }
    public bool ProperBoolean { get; set; }

    public Attachvariable()
    {
        RegisterProperties();
    }

    protected void RegisterProperties()
    {   
        RegisterProperty(value => UserID = value, () => UserID, "userID");
        RegisterProperty(value => Position = value, () => Position, "position");
        RegisterProperty(value => YesNo = value, () => YesNo, "yesno", (input) => input == "yes");
        RegisterProperty(value => ProperBoolean = value, () => ProperBoolean, "ProperBoolean", (input) => Boolean.Parse(input));
    }
}
Attachvariable obj = new Attachvariable();

obj.receiveData("userID", "9001");
obj.receiveData("position", "Hello World!");
obj.receiveData("yesno", "yes");
obj.receiveData("ProperBoolean", "True");

Console.WriteLine(obj.UserID); //9001
Console.WriteLine(obj.Position); //"Hello World!"
Console.WriteLine(obj.YesNo); //True
Console.WriteLine(obj.ProperBoolean); //True

obj.receiveData("yesno", "something else!");
Console.WriteLine(obj.YesNo); //False

obj.receiveData("ProperBoolean", "Invalid Boolean!"); //throws exception on `Boolean.Parse` step as intended
public interface IHookObj
{   
    void SetValue(string value);
    object GetValue();
}
class SomeCustomUsage : MasterClass
{
    public Person SomeoneUnimportant { get; set; }

    public SomeCustomUsage()
    {
        RegisterProperty(value => SomeoneUnimportant = value, () => SomeoneUnimportant, "SomeoneUnimportant", new PersonHook());
    }
}
public class PersonHook : HookObj<Person>
{
    protected override Person Parse(string value)
    {
        string[] parts = value.Split(',');
        var person = new Person(parts[0], parts[1]);

        if (person.FirstName == "Bob")
            throw new Exception("You have a silly name and I don't like you.");

        if (String.IsNullOrWhiteSpace(person.FirstName))
            throw new Exception("No first name provided.");

        if (String.IsNullOrWhiteSpace(person.LastName))
            throw new Exception("No last name provided.");

        return person;
    }
}
protected void RegisterProperty<T>(Action<T> setter, Func<T> getter, string name, HookObj<T> hook)
{
    hook.SetSetter(setter);
    hook.SetGetter(getter);
    dict.Add(name, hook);
}

protected void RegisterProperty<T>(Action<T> setter, Func<T> getter, string name, Func<string, T> inputParser)
{
    var hook = new CustomHook<T>(inputParser);
    RegisterProperty(setter, getter, name, hook);
}

protected void RegisterProperty(Action<string> setter, Func<string> getter, string name)
{
    var hook = new StringHook();
    RegisterProperty(setter, getter, name, hook);
}

protected void RegisterProperty(Action<int> setter, Func<int> getter, string name)
{
    var hook = new IntHook();
    RegisterProperty(setter, getter, name, hook);
}

protected void RegisterProperty(Action<float> setter, Func<float> getter, string name)
{
    var hook = new FloatHook();
    RegisterProperty(setter, getter, name, hook);
}
SomeCustomUsage customObj = new SomeCustomUsage();
customObj.receiveData("SomeoneUnimportant", "John,Doe");
Console.WriteLine(customObj.SomeoneUnimportant.LastName + ", " + customObj.SomeoneUnimportant.FirstName); //Doe, John

customObj.receiveData("SomeoneUnimportant", "Bob,Marley"); //exception: "You have a silly name and I don't like you."
customObj.receiveData("SomeoneUnimportant", ",Doe"); //exception: "No first name provided."
customObj.receiveData("SomeoneUnimportant", "John,"); //exception: "No last name provided."
Getter and Setter Methods in Model class

Getter and Setter Methods in Model class


By : Saul Goodman
Date : March 29 2020, 07:55 AM
it helps some times problem with your code you are creating multiple Model objects try this code
code :
   public StaffInformation(){
           ModelClass mc = new ModelClass();
            mc.setName("Khan");
            mc.setAge(30);
            mc.setAddress("NY");
            Main.displayData(mc);

        }
  class Main{
    public static displayData(ModelClass mc)
    {
        System.out.println(mc.getAge());
        System.out.println(mc.getName());
        System.out.println(mc.getAddress());

    }
    public static void main(String[] args) {
    StaffInformation sc=new StaffInformation();
    }
    }
Forcing class methods use setter/getter of its own private member

Forcing class methods use setter/getter of its own private member


By : Coder
Date : March 29 2020, 07:55 AM
will be helpful for those in need You can't do this directly.
One approach would be to create a base class MyBaseClass which has the member _x marked private and code the accessors, along with the mutual exclusion object, in MyBaseClass.
Related Posts Related Posts :
  • Template engine recommendations
  • Help with hash tables and quadratic probing in Java
  • javax.persistence.NoResultException: getSingleResult() did not retrieve any entities
  • What does look and feel (java swing) mean?
  • Android Lightweight HTML Template Engine
  • Setting unique key constraint for Db4oEmbedded EmbeddedConfiguration
  • How can I handle user defined exceptions and after handling them resume the flow of program
  • Latest org.json
  • How to create web service client in a .jsp page?
  • Java Runtime command line Process
  • Android: add badge to icons internal to my app
  • spymemcached - is it possible to disable the logging system?
  • Java Logger with Servlets
  • replace special characters in string in java
  • why won't Eclipse use the compiler I specify for my project?
  • Google Web Toolkit, what can I do with it?
  • doubt on private members and Methods
  • How do I check if output stream of a socket is closed?
  • Is there a clean cut way of adding NOP records to an AFP file using Java?
  • Move multiple BufferedImage in Java2D?
  • how to learn Drools or another rule engine fast
  • Date Sorting - Latest to Oldest
  • unable to add objects to saved collection in GAE using JDO
  • Spring, Hibernate, Blob lazy loading
  • Including Applet in JSP page
  • Original object is also changed when values of cloned object are changed
  • Drag and drop + custom drawing in Android
  • Creating a time series with jfreechart
  • Hibernate Criteria: Perform JOIN in Subquery/DetachedCriteria
  • How to check if my string is equal to null?
  • Connect two client sockets
  • How to reference a .dll from a .jar file
  • Invoke web-services in JSF
  • servlet connection to DB
  • Can I un-assign (clear) all fields of an instance?
  • Java parsing XML document gives "Content not allowed in prolog." error
  • Deploy Play! application as executable jar
  • Castor: how to map a simple list of strings?
  • Hibernate Transient Extends problem
  • Posting a JSON array to webservice in Android
  • How to search for duplicate values in a huge text file having around Half Million records
  • Easy way to get a test file into JUnit
  • cast across classloader?
  • Image manipulation
  • Java - JPA - Generators - @SequenceGenerator
  • What's a good Java-based Master-Slave communication mechanism?
  • Design Help/Suggestion required
  • NullPointerException in com.sun.tools.jxc.SchemaGenTask
  • time required to finish the multithreaded program?
  • Traditional IO vs memory-mapped
  • Using StringBuilder to process csv files to save heap space
  • Response Time is different for mulitiple execution of the application with the same request Performance problem
  • Java - Weblogic - JMX : request available free memory on all servers
  • Error: Can't find common super class of
  • JNI problem when calling a native library that loads another native library
  • calling Stanford POS Tagger maxentTagger from java program
  • Notification framework for java
  • hide keyboard in android?
  • Alternative of JPA
  • How to get Java XP Look and Feel
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk