Accessing methods from / within difference classes, newb - java

I am still fairly new to java, so please bear with me.
I am having trouble understanding why it is that I can only access certain methods / functions that belong to an instance of an object from certain classes / places/. Once I create an instance of an object and then press the dot "." operator it does not bring up all the methods that I want to use for it, (I want to see all the methods that the objects class inherits and implements.)
For example:
// In a junit test class, I make an instance of the class DailyLog which takes 2
// integers
private DailyLog log; // which seems fine for now, but when I add on the next
// line:
log = new DailyLog (5,500); // It gives me an error on the semicolon on the line
// above saying "- Syntax error on token ";", , expected"
I do not understand why it will not let me create an instance of DailyLog and set it's paramaters...?
Question 2: If I just leave the first line of code in, then set the parameters of log within a method in the same class, it lets me set it's parameters, but when I press the "." operator, It does not show me the size function, which is the function I want to use. - I thought it would inherit size from a superclass, so why does it not let me use it?
Question 3: I have a method within the dailyLog class called variance, and another called numInsertions, I need to use the numInsertions method within the variance method, but when I write below, the only way I can get to the numInsertions method is through another method, and this will not work as i need to access the numInsertions method to directly to assign it's value to b, not through another method as this will change it's value.
public Integer variance() throws SimulationException{
Integer a = log.
I think it might have to do with scope, when I have another class which creates an instance of dailyLog, and when I press the ". operator on it, it gives some methods to use from the daulyLog class and it's superclass, but not all of them. I find this quite confusing, and help would be appreciated, thanks.
UPDATE**
Maybe putting more code here will help to illustrate my problem:
public class dailyLog implements Log{
private Integer userLogSize1;
private Integer maxEnt;
private ArrayList<Integer> log = new ArrayList<Integer>();
public dailyLog (Integer userLogSize, Integer maxEntry) throws SimulationException{
if ((userLogSize<= 0 || maxEntry <= 0)){
throw new SimulationException("message goes here");}
this.log = new ArrayList<Integer>(userLogSize);
for (Integer i = 0; i <= userLogSize; i++){
log.add(null);}
userLogSize1= userLogSize;
maxEnt = maxEntry;
}
public Integer numInsertions(){
Integer total = 0;
for (Integer i = 0; i < log.size(); i++){
if (log.get(i) != null){
total++;}}
return total;}
// *** below I want to write log.numentries but i cannot, why it this? I can only write
// log.get(numentries()) but that gives the wrong answer.
public Integer variance() throws SimulationException{
if (log.size() == 0){
throw new SimulationException ("Put message here");}
Integer a = log.get(0);
Integer b;
Integer d = log.get(1);
if (d == null){
b = log.get(numInsertions()-1);}
else {b = log.get(numInsertions()-2);}
Integer c = log.get(userLogSize1-1);
if ( c == null){
return a - b;}
return a-c;}
}

I think you are seeing the different protection levels in Java. For the members and methods of a class, there are generally four protection levels: private, public, protected, package-private. If a method or object is not prefixed with one the keywords private, public, protected, then it is by default package-private.
A method or class member which is private can only be referenced within the same class in which it is declared.
A method or class member which is public can only be referenced from any class in any package.
A method or class member which is protected can only be referenced from the same class and subclasses.
A method or class member which is package-private can only be referenced from within the same package. If you are developing with the default package (that is, you have not declared a package), then your code will generally treat package-private exactly as it would treat public, since all classes are defaulted to the default package.
Here is a reference and here is another question which explains the same ideas in less words.

if you're trying to pass a method from one class to the other, and you don't want to make it static, meaning it would be shared across all instances, you can create a new instance of the class in a different class. For example say you have class A and class B:
public class A {
private int a;
private void setA(int a) {
this.a = d;
and class B:
public class B {
private int b;
private void setB(int b) {
this.b = b;
so then I can call all of class A's methods by invoking a constructor from it:
public class B {
///Constructor line
private A a = new A();
A.setA(10);
System.out.println(A.a); ///should print 10

You need to understand modifiers (i.e. private, public, protected, and package-level). Every field of a class and method of a class (both static and non-static) has a modifier. If you don't specify one, then it is "package-level". You don't specify modifiers inside a code block (e.g. a method body) because it is assumed that the scope of such variables is the inside block. Just a quick example of a block-scope, the following is legal in Java:
public int foo(){
{
int max = 0;
for(int i = 0; i < 10; ++i)
if(i > max)
max = i;
}
final int max = -10;
return max;
}
In a nutshell you have the following (note that constructors would be considered methods in the following):
public: Anything can access this method or field. For fields, this means any class can set this field unless it's declared final. You should be very aware though that even an object declared final can be modified (such as an array or any other mutable object). For methods, this simply means any class can call this method.
private: Only this class can access this field or method. This means that the only place you can modify these fields or call these methods is within this class file. An instance of this class can access fields from another instance of this class (through some method written inside this class's body that references some other object instance of this class).
protected: Any class that is either in the same package as this class or a subclass of this class (could be in a separate package) has direct access to a protected field or method.
package-level: To specify package-level access, you do not specify any modifier at all (i.e. public, private, or protected...nothing). In this case, any class within this package has access to this field or method.
The better question is when should you use which? Most methods should be public and most fields should be private as a general rule. You should be very weary of people who claim that these things are for "security". The only way to ensure data integrity of an object is to only return primitive values or immutable objects or copies of mutable objects. As a quick example, let's say you implement an ArrayList (a dynamic array). Internally, you probably have an array object such as private int[] arr. If you return this array object in any public method then you run the risk of the calling class modifying the internal array and making your ArrayList inconsistent.
I would follow these guidelines:
Fields
public: Only declare a field public if it is also final and an immutable object or primitive. This should be used for persistent objects who's field never changes (i.e. once it's set in the constructor this public final field will never be changed).
protected: This should primarily be used in abstract classes. That is the abstract class declared a data structure which its subclasses can use and reference (and modify). If this is something like a list it may still be appropriate to declare it final (that is something the sub-class can modify, but not reassign).
package-level: This should primarily be used by auxiliary classes in a package. They generally shouldn't be final (although if they are things like a list that may be appropriate). As a quick example. If you implement a heap, you may want the heap nodes to hold information about what element they are storing and where they are in they heap's array. The heap is really responsible for setting this, so by declaring it package level, your heap implementation can directly access and reassign things like the heap index and heap value for each of its heap nodes.
private: Private fields are most common. Most fields should be private. This means that only methods in this class file can modify or reassign this field. This should be used when you want to guarantee the behavior of a class. If you use any other modifiers, then the behavior of this class's data may be dictated by other classes.
As for methods, it's pretty simple. A public method should be something that any class can call to query the object without disrupting the data integrity of the object (i.e. the method should not be capable of putting the object into an inconsistent state which means public methods should not, in general, return mutable fields). Private, protected, and package-level methods should all be helper methods which are used to improve modularity. Basically it depends on "who" you trust. If the method is private then you only trust this class to call it correctly. If it's package level, then you only trust classes in this package to call the method correctly. And finally if it's protected, then you only trust classes in this package and sub-classes to call this method correctly.

Related

Can I use a non-static method in another non static method? [duplicate]

I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?
Could someone please explain to me in really simple terms what Static or Class Methods are?
Also, could I get a simple explanation on what Instance methods are?
This is what they give me in the textbook:
There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.
The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass(); //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Difference between Static methods and Instance methods
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call.
Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'.
Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If state of a method is not supposed to be changed or its not going to use any instance variables.
You want to call method without instance.
If it only works on arguments provided to it.
Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.
The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object.
e.g:
Myclass.get();
In instance method each object will have different behaviour so they have to call the method using the object instance.
e.g:
Myclass x = new Myclass();
x.get();
Static Methods vs Instance methods
Constructor:
const Person = function (birthYear) {
this.birthYear = birthYear;
}
Instance Method -> Available
Person.prototype.calcAge = function () {
2037 - this.birthYear);
}
Static Method -> Not available
Person.hey = function(){
console.log('Hey')
}
Class:
class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}
/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}
The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :)
Same is the case with variables.

What does it mean to say the keyword "private" is private at the class level?

A source I am reading says that the keyword private means a method or variable is private at the class level, not the object level.
Meaning in a chunk of code like this:
public class Weight2 implements Comparable<Weight2>
{
private int myPounds, myOunces;
public Weight2()
{
myPounds = myOunces = 0;
}
public Weight2(int x, int y)
{
myPounds = x;
myOunces = y;
}
public int compareTo(Weight2 w)
{
if(myPounds<w.myPounds)
return -1;
if(myPounds>w.myPounds)
return 1;
if(myOunces<w.myOunces)
return -1;
if(myOunces>w.myOunces)
return 1;
return 0;
}
}
A Weight2 object can access the private fields of a different weight2 object without an accessor method... but rather by just saying w.myPounds.
CLARIFICATION:
I want to know from where objects can access a different object's private data. Is it only from within the class? Or could this be done from a driver program?
A source I am reading says that the keyword private means a method or
variable is private at the class level, not the object level.
I don't know your source. It is not wrong but it is not clear either.
You could refer to the JLS that bring this information about the private modifier :
Chapter 6. Names
6.6.1. Determining Accessibility
... the member or constructor is declared private, and access is
permitted if and only if it occurs within the body of the top level
class (§7.6) that encloses the declaration of the member or
constructor.
About :
So what I mean to ask is, can objects of the same type access each
other's private fields without accessor methods?
Indeed.
And it is rather consistent with the specification.
It doesn't restrict the access to private members to only the current instance.
So, you may consider that this limitation doesn't exist and so you can invoke private method for current instance or any variable referencing the current class.
And it is of course true in static as in instance contexts.
As a side note, you should also take into consideration the level access: class and instance.
The private static modifiers means a method or variable is private at the class level. So, you don't need any instance to refer it.
While the private modifier (without the static modifier) means a method or variable is private at the instance level.
So you need an instance to refer it.
So what I mean to ask is, can objects of the same type access each
other's private fields without accessor methods?
Yes, they can.
Access modifiers in Java are about Class'es, not about instances.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Not entirely sure what your question is exactly. However I will give you a basic summary of what i think you want.
If a variable or a method is private then it can only be accessed or used within the class in which it exists.
If a variable or a method is public then it can be accessed by other classes.
Have a look at this website it may assist you it certainly helped me.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

How do I call variables and methods from other classes?

I'm doing a homework assignment, and I need to create methods in one class "coinDispenser", and call them in the main class, "HW1"
I'm not sure how this works, however. This is a sample of my code in coinDispenser.java:
private int numNickles = 0;
And then calling the method later in HW1.java:
System.out.println("There are "+numNickles+" nickles in the machine.")
But I always get the error "numNickles cannot be resolved to a variable" and it wants me to create the integer in the HW1 class.
How do I call the integer from within HW1.java? Changing the integer to public int type doesn't make any difference.
Well, you definitely can't access a private member variable from one class to another. In order to access a public member in a different class, you need to either make a static variable and reference it by class, or make an instance of CoinDispenser and then reference that variable.
So, in CoinDispenser, it'd be:
public int numNickles = 0;
and in HW1, you'd have:
CoinDispenser cd = new CoinDispenser();
System.out.println("There are "+ cd.numNickles + " nickles in the machine.")
If you did a static variable you could also do:
CoinDispenser.numNickles
To call a method in another class, you have two options.
Option 1:
You can declare the method to be called as static, which means that it doesn't need to be called on an object.
NOTE: If you take this route, (which you shouldn't; it's generally bad to use static methods), you have to declare numNickles as static, meaning that there is only one instance of this field no matter how many CoinDispenser objects you create.
Example:
static void methodToCallName(any arguments it takes) {
//...do some stuff...//
}
Option 2: You can create an instance of the class using the new keyword which contains the method and call the method:
Example:
// in some method in the HW1 class (Which is a horrible class name, see java conventions)
CoinDispenser dispenser = new CoinDispenser(any parameters here);
coinDispenser.whateverYourMethodIsCalled(any arguments it takes);
The whole idea of classes in an object oriented language is to keep separate things separate. When you reference a variable defined in another class, you have to tell the program where it is.
I get the sense that you haven't really learned what it means to be object oriented, and you really should look more into it. You can't fake it; there is NO getting around object orientation. You must learn to love it. Sure, it can make simple things hard, but it will make hard things soo simple.
For the second bits of your question...
Please note that numNickles should in fact be private, contrary to what other users are saying.
Java best practices advocate encapsulation, which is basically a principle saying that other parts of your program should only be able to see what they need to and the inner workings of each class should not be exposed to other classes.
How do you achieve this? Simple; use accessor and mutator methods (getters and setters) to access and modify your fields.
// Define your field like usual...
private int numNickles = 0;
// ...and add these two methods...
public void setNumNickles(int value) {
numNickles = value;
}
public int getNumNickles() {
return numNickles;
}
This may seem like a lot of work for a variable, but many IDE's will automate the process for you, and it will save you from many frustrating bugs in the long run. Get used to it, because the rest of the Java world does it.
If numNickes is in another class you can't call it since it is scoped private.
If you want access to private scoped variables you have to write a method to return it. The convention is typically
public int getNumNickles(){
return numNickles;
}
This is by design and allows the protection of variables that you do not want to expose.
Your output would then be
System.out.println("There are "+myclass.getNumNickles()+" nickles in the machine.")
Alternatively you could make the variable public
public int numNickels;
But now it can be read from, and written to, by anyone using the class.
You are trying to access the field named numNickles from your CoinDispenser class (BTW CoinDispenser is the correct name for your java class). You can not directly access the fields and methods in your HW1 class. So, as MadProgrammer has indicated in the comment under your question, follow along as that.
In your HW1.java class have something like:
CoinDispenser cd = new CoinDispenser();
System.out.println("There are "+cd.getNumNickles()+" nickles in the machine.");
The "cd" in above line of code is your handle on the CoinDispenser class. With cd, you can access (by dotting) fields and methods from any class where you use the above lines. Further, you will still not be able to access the fields and methods in your CoinDispenser class if those fields and methods are "private".
The standard way to access a private field in another class is to use a getter method.
This would be like
private int numNickles = 0;
public int getNumNickles () {
return numNickles;
}
Also useful would be a setter method
public void setNumNickles (int numNickles) {
this.numNickles = numNickles;
}
Many IDE's (e.g. Eclipse) will automatically create these methods for you upon a click of a button.
These methods can then be called upon an instance of a CoinDispenser class.
CoinDispenser coinDispenser = new CoinDispenser ();
coinDispenser.setNumNickles (23);
System.out.println("There are "+ coinDispenser.getNumNickles() + " nickles in the machine.");
First of all, there is no variable name numNickels which cause the error to occur.
Second, to access the attribute of the class coinDispenser, you will need to create an object of that class, that is
coinDispenser a=new coinDispenser();
By doing so, you can then access public methods of the class coinDispenser. Considering that the attribute numNickles is private, you have two options, which is:
1. Change numNickles to public, then access it using
a.numNickles
2. Create a public method to get private attribute in class coinDispenser
public int getNumNickles() {return numNickles;}
and access it from HW1 using
a.getNumNickles()
Java is an Object-Oriented Programming language. This means in essence, that everything is based on the concept of objects. These objects are data structures that provide data in the form of fields and methods. Every class that you provide an implementation of, needs a form of an instance, to actually do something with it.
The following example shows that when you want to make an instance of a class, you need to make a call using newCoinDispenser(100). In this case, the constructor of the class CoinDispenser requires one argument, the amount of coins. Now to access any of the fields or methods of your newly made CoinDispenser, you need to call the method using variable.method(), so in this case coinDispenser.getCoins() to retrieve the title of our book.
public class CoinDispenser {
private int coins = 100; // Set the amount of coins
public int getCoins() {
return coins;
}
}
public class HW1 {
public static void main(String[] args) {
CoinDispenser coinDispenser = new CoinDispenser(100);
System.out.println("I have " + coinDispenser.getCoins() + " left.");
}
}
NB: We are using an extra method getCoins(), a getter, to retrieve the contents of the field coins. Read more about access level here.

Why variables are not behaving as same as method while Overriding.? [duplicate]

This question already has answers here:
why java polymorphism not work in my example
(3 answers)
Closed 6 years ago.
Generally Overriding is the concept of Re-defining the meaning of the member in the sub class.Why variables are not behaving like methods while Overriding in java ?
For instance:
class Base {
int a = 10;
void display() {
System.out.println("Inside Base :");
}
}
class Derived extends Base {
int a = 99;
#Override
// method overriding
void display() {
System.out.println("Inside Derived :");
}
}
public class NewClass {
public static void main(String... a) {
Derived d = new Derived();
Base b = d;
b.display(); // Dynamic method dispatch
System.out.println("a=" + b.a);
}
}
Since data member a is package access specified, it is also available to the Derived class. But generally while calling the overridden method using the base class reference, the method that is redefined in derived class is called (Dynamic method dispatch)..but it is not the same for the variable..why.?
EXPECTED OUTPUT
Inside Derived :
a=99
OBTAINED OUTPUT:
Inside Derived :
a=10
Prints 10 - why the variable does not behave similar to method in the derived class?
Why the variables are not allowed to be overridden in the sub class?
You typed b as an instance of Base. So when the compiler needs to resolve b.a, it looks to the definition of Base for the meaning of b.a. There is no polymorphism for instance fields.
Because the only thing that polymorphism ever applies to in Java is instance method.
Hence, you can neither override static members, nor the instance member fields. By, having these members in a derived class with the same names you're simply hiding them with a new definition.
System.out.println("a="+b.a);
Although, Base b may point to a sub-class object (at runtime) the a above has already been bound to Base class at compile time (static binding). Hence, it prints 10.
Variables behave like that because they lack behavior. In other words, variables are passive.
There is nothing about a variable's definition that a derived class can reasonably change by overriding:
It cannot change its type, because doing so may break methods of the base class;
It cannot reduce its visibility, because that would break the substitution principle.
It cannot make it final without making it useless to the base class.
Therefore, member variables declared in derived classes hide variables from the base class.
There is no way to override a class variable. You do not override class variables in Java you hide them. Overriding is for instance methods.
In this case, it might be a good idea to write a getter method:
public int getA(){
return 99;
}
Now you can override it in a derived class.
First, we don't override any class variable. Methods only.
Second, if you would like to see that the variable value has been updated or replaced, you should rather declare it as "static int" instead of "int". In this way, it will work as everybody is sharing the same variable, and the new value will be put on it.
Third, if you would like to see that the variable value being assigned and used differently, you could design it as passing a parameter in constructor, or something similar, to make it work accordingly as you desire.
The answer to this has to do with variable scoping, not polymorphism. In other words, you're overriding that variable in the class scope. So, d.a will return the variable in Derived's class scope, but b.a will return the variable in Base's class scope.
In OOP (Object Oriented Programming) the idea is to hide the data in the object and let object only communicate with invoking methods. That's why variables cannot be overloaded, in fact they are "scoped"/"attached" to a specific class.
Also the derived class should not define a again, it is already defined in the base class, so simply set a on the object to the desired value, e.g:
class Base {
private int a = 10;
public int getA() { return a; }
public void setA(inta) { this.a = a; }
}
class Derived extends Base {
// adding new variables, override methods, ...
}
// then later:
Derived d = new Derived();
d.setA(99); // override the default value 10
What would happen if variables could override other variables? Suddenly your class has to be aware of what variables the parent class is using, lest you accidentally override one and break whatever was using it in the parent class. The whole point of encapsulation is to avoid having that kind of intimate knowledge of another object's internal state. So instead, variables shadow same-named other variables, and which one you see depends on what type you're trying to reach the variable through.
There's hope, though. If all you want is to override the value, you don't have to redeclare the variable. Just change the value in an init block. If the base class is harmed by you doing that, then it chose the wrong visibility for that variable.
class Base {
int a = 10;
}
class Derived extends Base {
{ a = 99; }
}
Of course, this doesn't work very well for final variables.
we don't override any class variable. Methods only.
If you would like to see that the variable value has been updated or
replaced, you should rather declare it as "static int" instead of
"int". In this way, it will work as everybody is sharing the same
variable, and the new value will be put on it.
If you would like to see that the variable value being assigned and
used differently, you could design it as passing a parameter in
constructor, or something similar, to make it work accordingly as
you desire.
Moreover, if variables are overridden then what is left with a parent class of its own,it breaches the class security if java would give the access to change the value of variable of parent class.

Difference between Static methods and Instance methods

I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?
Could someone please explain to me in really simple terms what Static or Class Methods are?
Also, could I get a simple explanation on what Instance methods are?
This is what they give me in the textbook:
There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.
The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass(); //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Difference between Static methods and Instance methods
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call.
Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'.
Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If state of a method is not supposed to be changed or its not going to use any instance variables.
You want to call method without instance.
If it only works on arguments provided to it.
Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.
The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object.
e.g:
Myclass.get();
In instance method each object will have different behaviour so they have to call the method using the object instance.
e.g:
Myclass x = new Myclass();
x.get();
Static Methods vs Instance methods
Constructor:
const Person = function (birthYear) {
this.birthYear = birthYear;
}
Instance Method -> Available
Person.prototype.calcAge = function () {
2037 - this.birthYear);
}
Static Method -> Not available
Person.hey = function(){
console.log('Hey')
}
Class:
class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}
/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}
The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :)
Same is the case with variables.

Categories

Resources