Can A Static Method Be Overridden
Aug 26, 2014can a static method be overridden?
View Repliescan a static method be overridden?
View RepliesI would like to know what does it mean when a method is overridden by a class??Like for example when you append an object value to StringBuilder
View Replies View RelatedI am practicing OCPJP ....
import java.lang.*;
class InvalidValueException extends IllegalArgumentException {}
class InvalidKeyException extends IllegalArgumentException {}
class BaseClass {
void foo() throws IllegalArgumentException {
throw new IllegalArgumentException();
[Code] .....
Which one of the following options correctly describes the behavior of this program? And the answer is (definitely) --> The program will print : InvalidKeyException exception, but when i saw the explanation, it tells
It is not necessary to provide an Exception thrown by a method when the method is overriding a method defined with an exception (using the throws clause).
I don't know, but i think it will compiled because the Exception that is thrown by the foo method in DeriDeri class is inherited from unchecked exception.. so it is not necessary to declare throws statement on its method.. and if the exception was checked exception the answer must be different right?
For starters here is my code:
Java Code: class A {
int x=5;
}
class B extends A {
int x=6;
}
public class CovariantTest {
public A getObject() {
[Code] ....
And this is the output I get:
sub
5
I am unable to figure out how this is outputting 5 instead of 6. The getObject method of SubCovariantTest is obviously the one being called, and it returns a new B(). So why am I getting class A's x value? I thought since I was getting a B object returned that I would get B's x value.
I was following a tutorial for libGdx and suddenly became confused by the following syntax:
up.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y){
position.y += 1f;
//currentFrame = animation.getKeyFrame(12);
}
});
"up" is basically a text Button:
TextButton up = new TextButton("up", textButtonStyle);
and .addListener is just one of the methods "TextButton" has (actually I think its inherited from "Button" but that doesn't matter).
Basically my question is what's going on inside the parentheses? From what I see its a new instance of "ClickListener" but then suddenly they override an actual method within. Is this simply just a way to override a method from the ClickListener class or is it something else?
If a method is overridden but you use a polymorphic (supertype) reference to refer to the subtype object with the overriding method, the compiler assumes you're calling the supertype version of the method.
is this true? maybe i'm misunderstanding it, but i thought the JVM looks at the object at run time and checks the object type. the context of the quote is about checked exceptions, but it seems like the statement should stand regardless of context. but this doesn't back up my experience. for example:
public class Test{
public void print(){
System.out.println("Super");
} public static void main(String[] args){
Test t = new SubTest();
[Code] ....
Will invoke the subclass method. like i said, maybe i'm missing something.
I don't understand, why when in the constructor of the superclass A the method init() is called (line 4), the overridden version of the subclass is invoked (line 26) and not the superclass version (line 7):
class A {
public A () {
init();
}
public void init() {
System.out.println("test");
[Code] ....
I would have guessed that above code prints
test
1
But instead you get a NPE (because when the constructor of B is invoked
public static void main(String[] args) {
new B();
}
Then there is first the implicit call to super:
public B() {
s = " ";
init();
}
Which is the constructor of A:
public A () {
init();
}
But here now this init() method is not the version of A ( public void init() {
System.out.println("test");
}) but the overriden version of the subclass (B): public void init() {
System.out.println(s+=s.length());
}...
Which throws an NPE of course, because the initialization of s has not occured yet (it happens only after the implicit call to super() has finished (see public B() {
s = " ";
init();
}))
This is my code inside the method:
@Post
public static String getDetails(Representation entity) throws Exception {
String customerId = getQuery().getValues("cus_id");
}
I use this code in Restlet Representation. I try to get the value from the Request API. But I am facing the problem as "Cannot make a static reference to the non-static method getQuery() from the type Resource".
From what i understand static methods should be called without creating an instance of the same class . If so why would they return an instance of the same class like in the following : public static Location locateLargest(double[][] a) , the Location class being the same class where the method is defined . I don't understand this , does it mean that every field and every method in the class must be static ? Meaning that you cannot have instances of the class because everything is static . Or it's just a mistake and the class Location cannot have a static method: public static Location locateLargest(double[][] a) ?
View Replies View RelatedI can't figure out what this error message "Cannot make a static reference to the non-static method getEndUserCharge(long, long, long, long) from the type UpdateUserWS" actually means.
The error is coming from:
public void updateDetailsPackage() {
some unrelated code
long zero=0;
double endUserCharge=0;
endUserCharge = UpdateUserWS.getEndUserCharge(long zero, long zero, long zero, long zero); <-------- error is here
[Code] ....
Alright, I have two classes, this one
public class Player {
private String player;
public String getPlayer() {
return player;
}
private int strength;
private int defense;
[Code] .....
However, it says that under Player.getPlayer() that it 'Cannot make a static reference to the non-static method'.
Why I can create an Instance of a class that contains non static variables within the static main method ?
This program runs fine
import java.util.*;
public class Test{
public int j;
public static void main(String[] args) {
Test test1=new Test();
System.out.println(test1.j);
[Code] .....
I'm working on a banking program that is supposed to use 3 classes (Account-base class, CheckingAccount, and SavingsAccount) and several methods to display the banking information (ID, balance after a withdrawal and deposit, and the annual interest rate). This should be a pretty simple program, but I'm getting hung up on one portion of it. I'm getting some compiler errors, all of which deal with non-static variables being called from a static context (I'll also post these errors following the code). Up until the middle of last week, we just declared everything as static, but that's changed and I'm having trouble figuring out when to and when not to use static when declaring my methods, hence the compiler errors.
import java.util.Date;
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
private Date dateCreated = new Date();
[Code] ....
Here are the compiler errors I am receiving:
Compilation completed. The following files were not compiled:
6 errors found:
File: C:UsersHiTechRedneckDesktopSummer II 2014Computer Programming PrincipleProgram 5CheckingAccount.java [line: 7]
Error: non-static method getId() cannot be referenced from a static context
[Code] .....
I had a TestColor class which contained methods to change hue, saturation, brightness, red, green, blue of TestColor's instances but also had static methods which take in an additional parameter for an instance of TestColor and returns the affected instance of TestColor. Now instead of having one method for every possible color effect to be applied to an image, how can I have one method that takes in an Image parameter, a static or non-static method reference from TestColor parameter and lastly an intensnity value parameter. This is so that I can make an affectedImage object instance inside the method and a Graphics2D object for drawing to each pixel of the new image, now I have one for loop and one nested for loop for the x and y pixels of width and height of the old image and inside the nested for loop I'd create a TestColor by calling getRGB on the image's pixel. Then I would apply the static or non-static method reference somehow to change the color with the intensnity value and after applying it draw to the new Image with Graphics2D. How to would I parametize a method reference and be able to use it in such way?
View Replies View RelatedOne class having two method one as static n another as non-static, 2 threads are there t1 is accessing the static method and t2 the non-static method is it possible n both are sharing the same object.
I now we have two kinds of lock one is object level lock and another is class level lock
I am trying to compile the following code where the entry point is Main.java but i am getting the following error "Error non-static method add(int[]) cannot be referenced from a static context in Java " ....
If i add the keyword static in add method of A.java it works properly......
Class Main.java code
package com.company;
public class Main {
public int [] a= new int[]{1,2,3};
public static void main(String[] args) {
Main n= new Main();
[Code]...
Both the classes are in same package
class Test
{
static Test ref;
String[] arguments;
public void func(String[] args)
{
ref.arguments = args;
[code]...
This code run perfectly.But the static method is acessing a non static method which was supposed to be not possible.
We know that a non static method can not be directly refrenced from static method but in the example given below there is no such error.Why?
class A
{
private void display()
{
System.out.println("In A");
}
public static void invoke (A x)
{
x.display();
[code]....
In above case a non static method display() is being invoked from static method invoke ()but it is not giving error.why?
Which is more efficient static block or static method ?
View Replies View RelatedTake this:
class test
{
static int i=j;
static int j=10;
.....
this will give illegal forward reference ....
but this will compile successfully ..
class test
{
static int i=test1();
static test1()
{
return 20;
}
}
.....
plz assume we have main method in both cases ..
java would be loading all static members first and would be assigning default values .. and then will be running all the initializers from to bottom ..Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
I'm writing a program that calculates phone charges. I have my class is set up, but when I try to retrieve data from it in my main, eclipse says that I need to set my method to static, which messes up the rest of the program.
Class:
public class MobileCharges {
private double charges;
private int minutes;
private String plan;
[Code].....
in java why main method is always static in nature...
View Replies View Relatedclass One
{
public static void doStuff()
{
System.out.println("One");
}
}
class Two extends One
[code]....
My understanding of static says that static methods cannot be overrriden but the compilation of the above code results in Overriding rule violation error.
My teacher has asked me one question that "What is difference between the final method and static method".
View Replies View RelatedBook says static methods can not access object instance variables. But the following code successfully prints out
ba.balance = 10
instance var = 5.
It seems like Static method is able to access the instance variable of another class, as well as the instance variable of main class. What gives ?
class InitProcess {
public static void main(String[] args) {
mymethod();
}
int x = 5;
[code]....
I'm writing a code with a cellphone class to set price, brand and serial number. I'm also, in the main method, initializing 100 different cellphone in a matrix style ( up to here I'm fine). I have to use a copy constructor to define some cellphones ( fine too). Another thing I had to do was to generate random numbers and swap the price of the cellphones ( which I'm fine with too). My problem lies after using my static method. I have to display a new matrix with the changed price and return the counter that I used in my method to see how many times it was changed.
My two problems are that if I display my array again after I ran the method, it stays the same ( I didn't "catch" the change so I'm guessing the compiler just didn't keep them in the array). Secondly, I don't know how to return the counter. I don't have any ".getCounter" or something ( what I'm used to). Any input?
My formatting is terrible, I'm trying to improve it no need to point it out
Here's my code:
import java.util.Random;
//Cellphone Class ( apart from main method)
class Cellphone {
private String brand;
private long serialNumber;
private double Price;
//declaration of variables in cellphone class
[Code] ......