Class and accessor methods Java - java

I don't understand accessor methods and I'm stuck with creating setAge, getAge and getName.
This is the question:
Add three accessor methods, setAge, getAge and getName. These methods should set and get the values of the corresponding instance variables.
public class Player {
protected int age;
protected String name;
public Player(String namArg) {
namArg = name;
age = 15;
}
}

An accessor method is used to return the value of a private or protected field. It follows a naming scheme prefixing the word "get" to the start of the method name. For example let's add accessor methods for name:
class Player{
protected name
//Accessor for name
public String getName()
{
return this.name;
}
}
you can access the value of protected name through the object such as:
Player ball = new Player()
System.out.println(ball.getName())
A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word "set" to the start of the method name. For example, let's add mutator fields for name:
//Mutator for name
public void setName(String name)
{
this.name= name;
}
now we can set the players name using:
ball.setName('David');

Your instance variables are age and name. Your setter methods are void and set your passed arguments to the corresponding variable. Your getters are not void and return the appropriate variables.
Try this and come back with questions.

public class Player {
protected int age;
protected String name;
// mutator methods
public void setAge(String a) {
age = a;
}
public void setName(String n) {
name = n;
}
// accessor method
public string getAge() {
return age ;
}
public string getName() {
return name;
}
}

setAbcd methods are mutator methods which you use to set your protected data fields.
getAbcd methods are accessor methods which you use to return values of the data fields, as they are usually private and not available outside the class.
e.g
public void getvariableName() {
return variableName;
}

Answer for: I don't understand accessor methods
here is the thing:
why do we need accessor methods? Encapsulation !!!
Why do we need encapsulation?
1) Imagine you (programmer#1) gonna write those setAge, getAge and getName methods.
I am programmer#2. I most probably cant access age and name directly. So I have yo use your public accessor methods setAge, getAge and getName. This is to save your code and variables from mess. Cuz u cant trust all coders.
2) In setAge method u can provide VALIDATION
random evil programmer: ya I wanna make age equal to 234 so ur program results gonna crush hahaha
u: nah I gonna add validation condition into my setAge method so u can only make age equal from 0 to 90(whatever u want)
This is the most popular reason why we use accessor methods.
Code explanation:
setAge explanation( this is just to get main idea)
public void setAge(int ageInput) {
if ((ageInput > 10) && (ageInput <90))
{age = a;}}
Random evil programmer sends ageInput into your public method.
First of all, it checks if age value is correct. If yes, age instance(object) variable will become ageInput. If no, nothing will happen and your variables wont be messed up.
GetAge: it just returns current age value. Nothing fancy.
let me know if you have more questions ;) Best of luck to you.

Related

How can I associate two objects in main in Java [duplicate]

I'm from the php world. Could you explain what getters and setters are and could give you some examples?
Tutorial is not really required for this. Read up on encapsulation
private String myField; //"private" means access to this is restricted to the class.
public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}
In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':
class Dummy
{
private String name;
public Dummy() {}
public Dummy(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.
class Clock {
String time;
void setTime (String t) {
time = t;
}
String getTime() {
return time;
}
}
class ClockTestDrive {
public static void main (String [] args) {
Clock c = new Clock;
c.setTime("12345")
String tod = c.getTime();
System.out.println(time: " + tod);
}
}
When you run the program, program starts in mains,
object c is created
function setTime() is called by the object c
the variable time is set to the value passed by
function getTime() is called by object c
the time is returned
It will passe to tod and tod get printed out
You may also want to read "Why getter and setter methods are evil":
Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.
This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.
1. The best getters / setters are smart.
Here's a javascript example from mozilla:
var o = { a:0 } // `o` is now a basic object
Object.defineProperty(o, "b", {
get: function () {
return this.a + 1;
}
});
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.
2. Getters / setters in php
Example from sof
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
citings:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
http://tweener.ivank.net/
Getter and Setter?
Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.
package stackoverflow;
public class StackoverFlow
{
private int x;
public int getX()
{
return x;
}
public int setX(int x)
{
return this.x = x;
}
public void showX()
{
System.out.println("value of x "+x);
}
public static void main(String[] args) {
StackoverFlow sto = new StackoverFlow();
sto.setX(10);
sto.getX();
sto.showX();
}
}

Creating a superclass and subclass with constructors - Java

I am new to Java. I have a problem to solve, but I don't quite understand how constructors work. I understand how to create a superclass and a subclass but I don't understand the constuctors within them (or how they actually work - I have done rediculous amounts of research on constructors, but it's just not making much sense).
I am trying to write a program that creates a superclass called Employees. This Employee class has instance variables employeeId (which is an integer) and employeeName (which is a String).
The subclass is called Manager. The Manager subclass has an instance variable called employeeTitle (which is a String). It also has a method with the name of managerDetails(). ManagerDetails() is supposed to display the employeeId, employeeName, and the employeeTitle.
This is what I have so far:
package tryingoutjava;
public class TryingOutJava {
class Employee {
int employeeId;
String employeeName;
void Employee() {
}
}
class Manager extends Employee {
String employeeTitle;
void managerDetails() {
}
}
public static void main(String[] args) {
}
}
I am very confused on how to set up the constructors for the superclass and the subclass, or even what a constructor really looks like. I've seen examples all over the internet, but no one actually highlights the actual part that is the constructor, or how everything is linked visually, which is what helps me learn.
I guess I'm also having issues with understanding how to set up a method that calls on an object. If anyone has the time to help, it would greatly be appreciated. Thanks!
I guess you want something like this. Be noted, that it is a good idea to separate classes one-per-file in this case, as they are separate entities here. It is a good idea to limit data access to entity fields, as such using encapsulation.
Employee.java:
package tryingoutjava;
public class Employee {
// Protected access because we want it in Manager
protected int employeeId;
protected String employeeName;
public Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
Manager.java:
package tryingoutjava;
public class Manager extends Employee {
private String employeeTitle;
public Manager(String employeeTitle, int employeeId, String employeeName) {
// Use super to invoke Employee constructor
super(employeeId, employeeName);
this.employeeTitle = employeeTitle;
}
// Just create a simple string describing manager
#Override
public String toString() {
return "Manager{" +
"employeeTitle='" + employeeTitle +
"employeeId=" + employeeId +
", employeeName='" + employeeName + '\'' +
'}';
}
}
Application.java:
package tryingoutjava;
public class Application {
// Example of construction plus printing of Manager data
public static void main(String[] args) {
Employee davie = new Employee(1, "Dave The Cable Guy");
Manager tom = new Manager("CFO", 2, "Tomas");
System.out.println(tom.toString());
}
}
Constructors (most often than not) just delegate construction of parent through super invocation. While there are other techniques, like Builder pattern, this is the most basic and understandable approach. There are several other ways to do this, but this should get you started, hope it helps!
Purpose of Constructor
constructor is a method like other method but it is called when instantiate (or create a object from your class) for initialize your object for first use or later use. for example a class like Student must created (instantiated) when we give it name and family name for example. Without them, create a Student is not good because maybe we forget to give it proper name and use it incorrectly. constructor forces us to provide minimum things needed for instantiating objects from classes.
Constructor implementation in inheritance
About inheritance, it is different. When you want to create a Student which is a Human (extends Human) you must first create Human inside your Student and set special feature for your Student like ID which is not for Human (Human has name and etc). so when you create a Student with constructor, the super constructor (for Human) is called too.
What do we do in constructor
as I mentioned, we provide default value for our properties which must set them before creating and using object. (for using them properly) every subclass call super class constructor implicitly with super() but if super class doesn't have any default constructor (constructor with no argument) you must explicitly say super(...) at the first lien of subclass constructor (otherwise compile error)
What is the program steps when using constructor (Advanced)
super class static constructor and static variable (read by self if you want to know more about things I say here)
subclass class static constructor and static variable
super class variable and block constructor
super class constructors
sub class variable and block constructor
sub class constructors
I only mentioned 4 & 6.
I try to explain completely. My English is not good. I'm sorry.
If you know how a method works, then you know how a constructor works. The constructor is simply a special method that allows you to execute some code before the object is created.
Person p = new Person("Bob", 25); // Calls constructor Person(String name, int age)
Then in the constructor you can do things like assign initial values to any instance variables.
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
If the class is a subclass you need to call a constructor of the parent class before the object is created unless the parent class has a constructor with no parameter in which case java can call it for you if you don't specify anything. Here Worker extends Person.
private String occupation;
public Worker(String name, int age, String occupation) {
super(name, age) // Calls constructor Person(String name, int age)
this.occupation = occupation;
}
I guess you can achieve what you want in a single file via the code snippet below:
You can copy paste it in your code and it should work.
You can see how the constructor of parent class is being called by the help of super() and also the methods. Here I have used methods like getEmployeeTitle() which should help you get an overview on how to write methods. I have also overridden the toString() method so that you can understand how to override Object class' useful methods like toString().
Note : Although I have created all the classes in one code snippet for the sake of simplicity , but it is highly recommended that you create a separate file for each of these classes.
class Employee {
int employeeId;
String employeeName;
Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
class Manager extends Employee {
private String employeeTitle;
Manager(int employeeId, String employeeName, String employeeTitle) {
super(employeeId, employeeName);
this.employeeTitle = employeeTitle;
}
public String getEmployeeTitle() {
return employeeTitle;
}
#Override
public String toString() {
return ("employeeId: " + employeeId + ", employeeName: " + employeeName + ", employeeTitle" + employeeTitle);
}
}
public class TryingOutJava {
public static void main(String[] args) {
Manager manager = new Manager(007, "John Doe", " Sr. Manager");
System.out.println(manager);
System.out.println(manager.getEmployeeTitle());
}
}

how can i use a superclass method in a subclass java

public void setName (String n){}
public void setAfm (String a){}
These are the Superclass methods i need to call.
SalariedEmployee (){
name = super.setName(String n);
afm = super.setAfm(String a);
salary = payment();
And thats the constructor in the subclass. How can i call the methods properly. I don't want to use any parameters in SalariedEmployee, i want to set the name and afm with the superclass methods. But my methods are void. So i guess i have to change that right ? Or am I missing something else?
Thanks in advance!
EDIT : You can also use setters. The "super" keyword is mandatory only if you want to call a method from the superclass that you have overridden in the subclass.
You should use constructors to set initial values but using setters is a possible solution too :
class Employee {
String name;
String afm;
public Employee() {
}
public Employee(String name, String afm) {
super();
this.name = name;
this.afm = afm;
}
public void setName(String name) {
this.name = name;
}
public void setAfm(String afm) {
this.afm = afm;
}
}
class SalariedEmployee extends Employee {
//Using constructors
public SalariedEmployee(String name, String afm) {
super(name, afm);
salary = payment();
}
//using setters
public SalariedEmployee() {
setAfm("afm");
setName("name");
salary = payment();
}
}
Also a setter method like 'setName' should be void because you don't expect it to return anything unlike a getter method like 'getName' for example.
There are two cases when you want to call a super method. The first case is that the method was not overriden by the subclass. If that is the case, you can call those methods simply by calling
setName("Dick Aceman");
or
setAtf("Acebook");
It is more descriptive if you call them like this:
this.setName("Dick Aceman");
this.setAtf("Acebook");
The bulletproof way to call them is this:
super.setName("Dick Aceman");
super.setAtf("Acebook");
This last one works even if the methods were overriden, but in general it is considered to be too descriptive, so this kind of method call should be used only when there is no alternative. Note, that since your methods are public, they are inherited by subclasses.
The problems with your try were that:
you tried to assign the return value of the methods to variables, when the methods do not return values
you declared the type at method call, which is invalid
you used the undefined variables of a and n
You should watch a few tutorial videos, you will get the basics then. After you watch such a video or two, you should return to this answer.

What is the importance of constructors that creating in a same class?

I am very new to Java. I know the basic concepts of constructors. I know that, if we don't create any constructor also compiler will create default constructor.
I have created a program to check how this toString() method is usable,
public class Vehicle{
int rollNo;
String name;
int age;
public Vehicle(int rollNo, String name, int age){
this.rollNo=rollNo;
this.name=name;
this.age=age;
}
public String toString(){
return rollNo+""+name+""+age;
}
public static void main(String[] args){
Vehicle v=new Vehicle(100, "XXX", 23);
Vehicle v2=new Vehicle(101, "XXXS", 24);
System.out.println(v);
System.out.println(v2);
}
}
And, I am getting output as :
100XXX23
101XXXS24
But, my doubt is why are we creating constructor and passing same variables as arguments to that?
Why can't we assign the values to variables like this and can't we get values without constructor?
public class Vehicle{
int rollNo=100;
String name="XXX";
int age=23;
// public Vehicle(int rollNo, String name, int age){
// this.rollNo=rollNo;
// this.name=name;
// this.age=age;
// }
//
public static void main(String[] args){
// Vehicle v=new Vehicle(100, "XXX", 23);
// Vehicle v2=new Vehicle(101, "XXXS", 24);
Vehicle v=new Vehicle(rollno,name,age);
// Vehicle v2=new Vehicle();
System.out.println(v);
// System.out.println(v2);
}
public String toString(){
return rollNo+""+name+""+age;
}
}
Firstly, it is possible to set the values of attributes or properties without a defined constructor in the class definition. This can be done through the use of setters on the attributes/properties within a Java class. So for example:
public class Vehicle{
int rollNo;
String name;
int age;
// Note no constructor, so the default no-arg constructor can be used.
// Now the setters
public void setRollNo(int anInt) {
this.rollNo = anInt;
}
public String setName(String aName) {
this.name = aName;
}
public void setAge(int anAge) {
this.age = anAge;
}
public static void main(String[] args){
Vehicle v=new Vehicle(); // note no-arg constructor being used.
v.setRollNo(3);
v.setName("Hello");
v.setAge(12);
System.out.println(v);
}
}
The use of setters is far better as you adhere to an important OOP principle; that of encapsulation, which in Java and Software is quite critical.
Please have a look at the following Java Tutorial from Oracle that goes through the use of getters and setters and the use of constructors.
The main method is declared static, which means that it doesn't belong to any particular copy of your class. If you want to create copies of the class to use for whatever purpose, you use new, which causes the constructor to build a copy for you, and in your case set the appropriate variables (which belong to particular copies of the class, like the copies that you're holding in the v and v2 variables).
The fact that the main method is part of the same class is essentially irrelevant; main could be attached to any class, even an otherwise empty one.
The reason why you have to use Constructor having arguments is that created instance is immutable objects which means that whose state cannot be modified after it is created. In other words object does not have setter it only has getter methods.
In java platform GC is the main part of JVM, and immutable objects makes GS less work to clean the unusable objects in heap memory.
Pls refer to link http://c2.com/cgi/wiki?ImmutableObjectsAndGarbageCollection
The default constructor from the compiler will be the following.
public Vehicle()
If you don't define
public Vehicle(int rollNo, String name, int age)
then it won't exist and you can't use it.
Java does not create default constructors with arguments.

Java Public Var question [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Property and Encapsulation
NEWB Alert!!
I am starting with Android and Java and I am starting to understand it but I am wondering why I should use getters and setters and not just public variables?
I see many people make a private variable and create a get and set method.
What is the idea here?
Its called encapsulation and the concept is central to object oriented programming. The idea is that you hide the implementation of your class and expose only the contract i.e. hide the how and only expose the what. You hide the variables by making them private and provide public setters-getters and other public methods which the clients invoke to communicate with your class. They are not tied to the actual implementation of the methods or how you store your variables.
For example, suppose you had this class where you stored a phone number as a Long object:
public class ContactInfo {
private Long phoneNo;
public Long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = phoneNo;
}
}
Since the clients of the class only see the getter/setter, you can easily change the implementation of the class/methods by switching the phone number representation to a PhoneNumber object. Clients of ContactInfo wouldn't get affected at all:
public class ContactInfo {
private PhoneNumber phoneNo;
public Long getPhoneNo() {
return phoneNo.getNumber();
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = new PhoneNumber(phoneNo);
}
}
public class PhoneNumber {
private Long number;
public PhoneNumber(Long number) {
this.number = number;
}
public Long getNumber() {
return number;
}
}
The OOP concept involved is encapsulation (google it).
Some of the advantages are: you can specify different access level for setters (mutators) and getters (accessors), for example public getter and private setter. Another advantage is that you can add another code other than changing or retrieving the value. For example, you may want to check the validity of the set value, or you want to throw exceptions or raise some events in response to changing the variable to certain value. If you implement these inside an accessor or mutators, you can also change their implementations without changing any code outside of the class.
I believe the idea is "information hiding" http://en.wikipedia.org/wiki/Information_hiding
It also serves to control the access to variables (provides an interface). For example, you can provide a getter but not a setter, so that they may be read but not written. Whereas if everything was public any thing could read and write to the variables.
Also important is any checking/validation need to set a variable. For example you have a String name that is not allowed to be empty but if it is public it could easily be forgotten and set as name = "". If you have a setter such as public boolean setName(String newName) you can check newNames length and return true or false if it passes and is set or not
The concept is called encapsulation.
What it attempts to do is to separate the inner structure of a class from its behaviour.
For example, suppose a class like this
public class Point{
private float x;
private float y;
public float getX(){
return x;
}
public float getY(){
return y;
}
public float distanceToZero2(){
return x*x + y*y
}
public float getAngle(){
//havent considered the x = 0 case.
return atan(y/x);
}
public boolean isInFirstQuad(){
return x>0 && y>0;
}
}
In this case, encapsulation hides the inner structure of the class, and exposes only the operations available to a Point. If you dont like it, you can change its inner structure and mantain its behaviour (for example, changing carthesian coordinates to polar coordinates).
Anyoune who uses this class wont care about it, he /she will be happy that they have a Point class with this functionality.
Asides the encapsulation, you can also control the value get or set to your variable in some cases. For example, you want to validate the value of an age variable which should be >=1
class Person {
private int age = Integer.MIN_VALUE;
public void setAge(int age){
if(age>=1)
this.age = age;
}
public int getAge(){
return age;
}
}

Categories

Resources