Does the Subclass constructor inherit variables from the Superclass constructor? - java

Given:
public class Counter {
private int count;
public Counter() {
count = 5;
}
public void increment() {
count++;
}
public void reset() {
count = 0;
}
public int value() {
return count;
}
}
If I have a subclass with a defined function (not implicitly created), does the subclass constructor inherit the instance variable count from the superclass constructor? I ask this because I'm running into a bit of a confusion with regards to private count.
public class ModNCounter extends Counter {
int modCount;
public ModNCounter(int n) {
modCount = n;
}
#Override
public int value() {
return super.value() % modCount;
}
public static void main(String[] args) {
ModNCounter modCounter = new ModNCounter(3);
System.out.println(modCounter.value()); //prints out 5 % 3 = 2
modCounter.increment(); // count = 6
System.out.println(modCounter.value()); //prints out 6 % 3 = 0
modCounter.reset(); // count = 0
modCounter.increment(); // count = 1
System.out.println(modCounter.value()); //print 1 % 3 = 1
}
}
Does the object modCounter have a count variable? If not, why is modCounter.increment() not giving me an error?

An inherited class has all the members of its superclass, although they may not be directly accessible to it (if they are private). In this case - yes, an instance of ModNCount has a count member. It cannot access it since it's private, but, as you've seen, it can affect its value using the increment and reset methods.

Related

Why is this a static binding instead of dynamic binding?

I'm still a little confused with regards to the difference between static and dynamic. From what I know dynamic uses object while static use type and that dynamic is resolved during runtime while static is during compile time. so shouldn't this.lastName.compareTo(s1.lastName) use dynamic binding instead?
key.compareTo(list[position-1]) use dynamic binding
public static void insertionSort (Comparable[] list)
{
for (int index = 1; index < list.length; index++)
{
Comparable key = list[index];
int position = index;
while (position > 0 && key.compareTo(list[position-1]) < 0) // using dynamic binding
{
list[position] = list[position-1];
position--;
}
list[position] = key;
}
}
Why does (this.lastName.compareTo(s1.lastName)) use static binding?
private String firstName;
private String lastName;
private int totalSales;
#Override
public int compareTo(Object o) {
SalePerson s1 = (SalePerson)o;
if (this.totalSales > s1.getTotalSales())
{
return 1;
}
else if (this.totalSales < s1.getTotalSales())
{
return -1;
}
else //if they are equal
{
return (this.lastName.compareTo(s1.lastName)); //why is this static binding??
}
}
Your question isn't complete and doesn't include all relevant the code. However this is the basic difference between the different bindings
Java has both static and dynamic binding. Binding refers to when variable is bound to a particular data type.
Static/Early binding is done at compile time for: private, final and static methods and variables. And also for overloaded methods
Dynamic/late binding is done at runtime for: methods which can be overriden methods. This is what enables polymorphic behaviour at runtime.
To further demonstrate this point have a look at this code and see if you can determine when it would be early and late binding:
/* What is the output of the following program? */
public class EarlyLateBinding {
public boolean equals(EarlyLateBinding other) {
System.out.println("Inside of overloaded Test.equals");
return false;
}
public static void main(String[] args) {
Object t1 = new EarlyLateBinding(); //1
Object t2 = new EarlyLateBinding(); //2
EarlyLateBinding t3 = new EarlyLateBinding(); //3
Object o1 = new Object();
Thread.currentThread().getStackTrace();
int count = 0;
System.out.println(count++);
t1.equals(t2);//n
System.out.println(count++);
t1.equals(t3);//n
System.out.println(count++);
t3.equals(o1);
System.out.println(count++);
t3.equals(t3);
System.out.println(count++);
t3.equals(t2);
}
}
Answer:
++ is after the count and hence the result returned is the 0 before incrementing it. Hence starts with 0 and proceeds as you expect.
The only scenario where the equals methods of EarlyLateBinding object
is actually invoked is is statement 3.
This is because the equals method is overloaded (Note: the different
method signature as compared to the object class equals)
Hence the type EarlyLateBinding is bound to the variable t3 at
compile time.
.
in this code
public static void insertionSort (Comparable[] list)
{
for (int index = 1; index < list.length; index++)
{
Comparable key = list[index];
int position = index;
while (position > 0 && key.compareTo(list[position-1]) < 0)
{
list[position] = list[position-1];
position--;
}
list[position] = key;
}
}
key can be anything that implements the Comparable interface so in the compile time compiler doesn't know the exact type so type is resolved in the runtime by using the object that key referring to.
But in this code,
#Override
public int compareTo(Object o) {
SalePerson s1 = (SalePerson)o;
if (this.totalSales > s1.getTotalSales())
{
return 1;
}
else if (this.totalSales < s1.getTotalSales())
{
return -1;
}
else //if they are equal
{
return (this.lastName.compareTo(s1.lastName));
}
}
compiler knows the type of the s1 so it use the static binding

java: constructor cannot be applied to given types [duplicate]

I ve got the following code using arrays to find some prim numbers. However, when trying to compile my user class PalindromeArrayUser it says - "Constructor in class cannot be applied to given types"
required: int.
found: no arguments.
reason: actual and formal arguments lists differ in length.
However, I have passed to the constructer an int value (the same way it was designed in my blueprint). I don't quite get where the problem comes from. Thanks.
Here are my two classes
public class PalindromeArray
{
int arrLength;
public PalindromeArray(int InputValue)
{
arrLength = InputValue;
}
int arr[] = new int[arrLength];
boolean check[] = new boolean [arrLength];
public void InitializeArray()
{
for (int k = 2; k < arr.length; k++)
{
arr[k] = k;
check[k] = true;
}
}
public void primeCheck()
{
for (int i = 2; i < Math.sqrt(arr.length - 1); i++ )
{
if (check[i] == true)
{
for (int j = 2; j < arr.length; j++)
{
if (j % i == 0)
{
check[j] = false;
check[i] = true;
}
}
}
}
}
public void PrintArray()
{
for (int k = 2; k < arr.length; k++)
{
if ((!check[k]) == false)
System.out.println(arr[k]);
}
}
}
And this is my User class where the problem comes from. The class above compiles fine.
import java.io.*;
public class PalindromeArrayUser extends PalindromeArray
{
public static void main(String argv[]) throws IOException
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the upper bound.");
String line = input.readLine();
int InputUser = Integer.parseInt(line);
// this is where I pass the same int type as I
// constructed it
PalindromeArray palindrome = new PalindromeArray(InputUser);
palindrome.InitializeArray();
palindrome.primeCheck();
palindrome.PrintArray();
}
}
when you create a constructor for a class, there won't be any default constructor created for that class. so if you extend that class and if the subclass tries to call the no-arg constructor of its super class then there will be an compile-time error.
to demonstrate:
class Parent {
int i;
public Parent(int i) {
this.i=i;
}
}
class Child extends Parent {
int j;
public Child(int i, int j) {
super(i);
this.j=j;
}
public Child(int j) {
// here a call to super() is made, but since there is no no-arg constructor
// for class Parent there will be a compile time error
this.j=j;
}
}
EDIT:
to answer your question do this, don't assign the value arrLength to arr[] and check[] as arrLength would be 0 at that time.
so just declare them like this
int arr[];
boolean check[];
and in the constructor after you assign the input to arrLength put these statements.
arr = new int[arrLength];
check = new boolean [arrLength];
Error is because you extend PalindromeArray .This is not necessary.
Subclass (your PalindromeArrayUser) must provide constructor with one int.
If yous super class don't have default constructor then in you subclass constructors must invoke one of non-default constructor from super class. (super(params))
Error is because you are extending PalindromeArray, which has an explicit constructor. You must provide the constructor with argument.
Because there is no default constructor available in B, as the compiler error message indicates. Once you define a constructor in a class, the default constructor is not included. If you define any constructor, then you must define all constructors.
Read more here
Disclaimer: The above is taken from the article

Incrementing a number and then setting back after fixed records arre entered?

Actuallt I want to set a varaiable as 6 digit number, incrementing it and resetting it back whent the record reaches 999999. I want to increment the value only when I perform a certain call to the web service through my client that is written in Java. Can you please suggest any method for doing? Any other way then creating a database and entering the value in that and then flushing the values when the count reaches 999999.
Thanks
I'll write an example in a singleton but I recommend using spring or container equivalent to use 1 single bean to do this.
public class Counter {
private static Counter instance;
private static int COUNT_MAX_VALUE = 1000000;
public static synchronized Counter getInstance() {
if (instance == null) {
instance = new Counter();
}
return instance;
}
// -- end of static features --
private int counter;
public Counter() {
this.counter = 0;
}
// return result
public synchronized int getCount() {
return counter;
}
// increment by 1, then return result
public synchronized int addAndGetCount() {
addCount();
return getCount();
}
// increment by 1
public synchronized int addCount() {
if (++counter >= COUNT_MAX_VALUE) {
counter = 0;
}
}
}

Is it possible to link integers from a method to a class?

I have a quick question out of curiosity...if I declare an integer in one method, for example: i = 1, is it possible for me to take that i and use its value in my main class (or another method)? The following code may be helpful in understanding what I'm asking...of course, the code might not be correct depending on what the answer is.
public class main {
public main() {
int n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
No you cannot! Not unless you make it an instance variable!
Or actually send it to the function as an argument!
First, let's start simple. All methods that are not constructors require a return type. In other words,
public void number(){
i = 1;
}
would be more proper.
Second: the main method traditionally has a signature of public static void main(String[] args).
Now, on to your question at hand. Let's consider a few cases. I will be breaking a few common coding conventions to get my point across.
Case 1
public void number(){
i = 1;
}
As your code stands now, you will have a compile-time error because i is not ever declared. You could solve this by declaring this somewhere in the class. To access this variable, you will need an object of type Main, which would make your class look like this:
public class Main {
int i;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
i = 1;
}
}
Case 2
Let's say you don't want to make i a class variable. You just want it to be a value returned by the function. Your code would then look like this:
public class Main {
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
}
public int number(){ //the int here means we are returning an int
i = 1;
return i;
}
}
Case 3
Both of the previous cases will print out 1 as their output. But let's try something different.
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
int i = 1;
}
}
What do you think the output would be in this case? It's not 1! In this case, our output is 0. Why?
The statement int i = 1; in number(), it creates a new variable, also referred to as i, in the scope of number(). As soon as number() finishes, that variable is wiped out. The original i, declared right under public class Main has not changed. Thus, when we print out myMain.i, its value is 0.
Case 4
One more case, just for fun:
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
System.out.print(myMain.i);
}
public int number(){
int i = 1;
return i;
}
}
What will the output of this be? It's 10. Why you ask? Because the i returned by number() is the i in the scope of number() and has a value of 1. myMain's i, however, remains unchanged as in Case 3.
You may use a class-scope field to store you variable in a class object or you can return it from one method or pass it as a parameter to the other. Mind that you will need to call your methods in the right order, which is not the best design possible.
public class main {
int n;
int i;
public main() {
n = 1;
System.out.print(n + i);
}
public number(){
i = 1;
}
}
Yes, create a classmember:
public class Main
{
private int i;
public main() {
int n = 1;
System.out.print(n + i);
number();
System.out.print(n + i);
}
public number(){
i = 1;
}
}
void method(){
int i = 0; //has only method scope and cannot be used outside it
}
void method1(){
i = 1; //cannot do this
}
This is because the scope of i is limited to the method it is declared in.

Constructor in class cannot be applied to given types

I ve got the following code using arrays to find some prim numbers. However, when trying to compile my user class PalindromeArrayUser it says - "Constructor in class cannot be applied to given types"
required: int.
found: no arguments.
reason: actual and formal arguments lists differ in length.
However, I have passed to the constructer an int value (the same way it was designed in my blueprint). I don't quite get where the problem comes from. Thanks.
Here are my two classes
public class PalindromeArray
{
int arrLength;
public PalindromeArray(int InputValue)
{
arrLength = InputValue;
}
int arr[] = new int[arrLength];
boolean check[] = new boolean [arrLength];
public void InitializeArray()
{
for (int k = 2; k < arr.length; k++)
{
arr[k] = k;
check[k] = true;
}
}
public void primeCheck()
{
for (int i = 2; i < Math.sqrt(arr.length - 1); i++ )
{
if (check[i] == true)
{
for (int j = 2; j < arr.length; j++)
{
if (j % i == 0)
{
check[j] = false;
check[i] = true;
}
}
}
}
}
public void PrintArray()
{
for (int k = 2; k < arr.length; k++)
{
if ((!check[k]) == false)
System.out.println(arr[k]);
}
}
}
And this is my User class where the problem comes from. The class above compiles fine.
import java.io.*;
public class PalindromeArrayUser extends PalindromeArray
{
public static void main(String argv[]) throws IOException
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the upper bound.");
String line = input.readLine();
int InputUser = Integer.parseInt(line);
// this is where I pass the same int type as I
// constructed it
PalindromeArray palindrome = new PalindromeArray(InputUser);
palindrome.InitializeArray();
palindrome.primeCheck();
palindrome.PrintArray();
}
}
when you create a constructor for a class, there won't be any default constructor created for that class. so if you extend that class and if the subclass tries to call the no-arg constructor of its super class then there will be an compile-time error.
to demonstrate:
class Parent {
int i;
public Parent(int i) {
this.i=i;
}
}
class Child extends Parent {
int j;
public Child(int i, int j) {
super(i);
this.j=j;
}
public Child(int j) {
// here a call to super() is made, but since there is no no-arg constructor
// for class Parent there will be a compile time error
this.j=j;
}
}
EDIT:
to answer your question do this, don't assign the value arrLength to arr[] and check[] as arrLength would be 0 at that time.
so just declare them like this
int arr[];
boolean check[];
and in the constructor after you assign the input to arrLength put these statements.
arr = new int[arrLength];
check = new boolean [arrLength];
Error is because you extend PalindromeArray .This is not necessary.
Subclass (your PalindromeArrayUser) must provide constructor with one int.
If yous super class don't have default constructor then in you subclass constructors must invoke one of non-default constructor from super class. (super(params))
Error is because you are extending PalindromeArray, which has an explicit constructor. You must provide the constructor with argument.
Because there is no default constructor available in B, as the compiler error message indicates. Once you define a constructor in a class, the default constructor is not included. If you define any constructor, then you must define all constructors.
Read more here
Disclaimer: The above is taken from the article

Categories

Resources