SO,letsay we have a bicycle superclass with cadence 0 and 3 subclasses.I want the "trotineta" sbuclass to have cadence 5 while the other 2 subclasses cadence remains 0.
Why isnt this working?
class Trotineta extends Bicycle{
Bicycle.cadence = 5;
}
You haven't shown the definition of Bicycle.cadence, but based on the syntax, I'm assuming it's a static member. If you change a static member of the base class, all instances of all sub-classes will be affected by this change, since a static member has a single value for all instances of the class.
Now, if cadence wouldn't be static, you can give it a different value in the constructor of Trotineta (assuming the sub-class has access to that member).
public Trotineta ()
{
cadence = 5;
}
This would be somewhat wasteful, though, since each instance of Bicycle would have its own cadence member.
You can create getter and setter or just use word super
public class TestONE extends TestTWO {
{
super.gg = 4;
}
public static void main(String[] args) {
System.err.println(new TestONE().gg);
}
}
class TestTWO {
static int gg = 0;
}
or
public class TestONE extends TestTWO {
public static void main(String[] args) {
TestONE.setGg(5);
System.err.println(new TestTWO().gg);
}
}
class TestTWO {
protected static int gg = 0;
public static int getGg() {
return gg;
}
public static void setGg(int gg) {
TestTWO.gg = gg;
}
}
class Bicycle{
int cadence = 0;
/* since no access modifier is mentioned, by default cadence becomes
package private ie; it cannot be accessed outside the package
in which it is defined now*/
}
class Trotineta extends Bicycle{
Bicycle.cadence = 5;
/* you cannot do this as cadence is not a static
attribute of class Bicycle*/
}
// Below is one of the possible solutions
class Trotineta extends Bicycle{
/*below code can also be written in a method but not outside as you have
written in your example code*/
{
this.cadence = 5;
//here 'this' is the current instance of Trotineta
}
}
Related
In C++ I could use 1 class throughout multiple files and when I modify a value using a function from one file, it would change that value globally.
In Java every file has to have it's own class; when I change a value using a method from one file, it does not change this value globally.
For example in C++ the files might look like this:
someClass.h
class someClass{
private:
int x;
public:
//Constructor
someClass(){
x = 5;
}
void changeVariable(); //Declaring function for later
}
main.cpp
int main(){
someClass cClass;
cClass.changeVariable(); //Call function
cout << x; //outputs 6
}
fileA.cpp
void someClass::changeVariable(){
x = 6; //x is changed to 6 globally.
}
In Java:
someClass.java
public class someClass {
int x;
//Constructor
public someClass() {
x = 5;
}
main.java
public class main {
public static void main() {
someClass cClass = new someClass();
subClass cSub = new subClass();
cSub.changeVariable();
System.out.print(x); //outputs 5
}
}
fileA.java
public class fileA extends someClass {
void changeVariable() {
x = 6; //x is changed to 6 only for fileA
}
}
My question is how can I change a variable from the sub class so that the variable is changed globally (For Java). Sorry if the question is still confusing.
Try with this:
public class someClass {
static int x;
//Constructor
public someClass() {
x = 5;
}
That a variable where static means that its value is common for all objects of the same class. That only one variable x is created for all, not one for each object.
Read that answer if you want a good explication of what static means:
What does the 'static' keyword do in a class?
Expose a function. setXyz in parent
public class someClass {
int x;
//Constructor
public someClass() {
x = 5;
}
public void setX(int n){
this.x = n;
}
}
public class fileA extends someClass {
void changeVariable() {
setX(6);
}
No need for static variable, this is the most equivalent thing you can do in Java:
public abstract class SomeClass {
protected int x = 5;
public abstract void changeVariable();
}
public class FileA extends SomeClass {
#Override
public void changeVariable() {
x = 6;
}
}
SomeClass doesn't have to be abstract of course, but you would have to implement it's changeVariable method.
Also x cannot be private, it has to be protected, so that it can be accessed by subclasses.
public interface Bsuper {
abstract class A {
abstract void test1();
void test2() {
System.out.print("test2 ");
}
}
}
// second file
public class Bsub extends Bsuper.A {
void test1() {
System.out.print("test1 ");
}
}
// third file
public class Bsubmain {
public static void main(String args[]) {
Bsub sub1 = new Bsub();
Bsuper.A obj = new Bsub();
sub1.test1();
sub1.test2();
obj.test1();
obj.test2();
}
}
It produces the output as expected test1 test2 test1 test2, but my question is in the Bsuper class, class A is static we all know that and now with the abstract keyword it becomes abstract class, but how is it possible to have both abstract and static applied to class at the same time.Is class A really static also or is there any other explanation for it.Please answer!!
how is it possible to have both abstract and static applied to class at the same time.
It is perfectly valid to have a static abstract class. This is different from having a static abstract method, which doesn't make sense, as you can't override such methods, and you're also making it abstract. But with static class, you can of course extend it, no issues. Making it abstract just restricts you with creating an instance of it.
So, even this is valid:
class Main {
static abstract class Demo { }
class ConcreteDemo extends Demo { }
}
In which case, you can't instantiate Demo, and sure you can instantiate ConcreteDemo.
Remember that a static inner class is using a different concept of static.
In this case it means that the inner class does not have access to the outer class's instance variables.
public class Test {
long n = 0;
static class A {
// Not allowed.
long x = n;
}
class B {
// Allowed.
long x = n;
}
}
Making them abstract does not change anything.
abstract static class C {
// Not allowed.
long x = n;
}
abstract class D {
// Allowed.
long x = n;
}
Base Class;
import java.util.Random;
public class Animal
{
public void move()
{
int value = 0;
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
}
Inherited Class;
public class Cat extends Animal
{
public void moveCat()
{
super.move();
System.out.println("Move Cat");
}
public static void main(String[] args)
{
Cat test = new Cat();
test.moveCat();
}
}
I Am trying to use a value of the base class animals method move in the override method moveCat. Why cant I use the value "value" in moveCat from Cat.
For Example;
public void moveDoodle()
{
super.move();
System.out.println("Move Doodle");
if(value == 1)
{
System.out.println("Value from base");
}
}
If I am grabbing the content from the base method why can't I also use the values. If its not possible what should I be doing instead in order to get the values I need.
That's because value is in the local scope of the method move() of your base(Animal) class and that is why its not inherited. Only the instance variables will be inherited(provided they are not private). Thus, you need to make value an instance variable for you to be able to inherit it in your base(Animal) class.
int value = 0;
public void move()
{
// int value = 0;
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
Note: I can see that you've inherited the Animal class but have not overriden any method, contrary to what was suggested in the question title.
because value is a local variable to method move(). Local variables are not inherited. Create the variable as instance variable.
By the way, if you are trying to override to move() method, you need to keep the same method signature.
import java.util.Random;
public class Animal {
int value = 0;
public void move() {
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2) + 1;
}
}
Your Cat class
public class Cat extends Animal {
public void moveCat() {
super.move();
System.out.println("Move Cat");
}
public static void main(String[] args) {
Cat test = new Cat();
test.moveCat();
System.out.println(test.value);
}
}
With your implementation, the value variable is of local scope. It is accessible only within the move method and the outer world doesn't know about this.
You will need to declare this variable at the instance scope in order to make it accessible at the class level. You will also need to declare the access modifier for this so that the inheriting class know about it.
The following will work.
protected int value = 0;
public void move()
{
System.out.println("Move");
Random rand = new Random();
value = rand.nextInt(2)+1;
}
As I understand the inherited class should also inherit variables, so why doesn't this code work?
public class a {
private int num;
public static void main(String[] args) {
b d = new b();
}
}
class b extends a {
public b() {
num = 5;
System.out.println(num);
}
}
num variable's access modifier is private and private members are not accessible out of own class so make it protected it will accessible from subclass.
public class a {
protected int num;
...
}
Reference of Controlling Access to Members of a Class
As i understand the inherited class should inherit also variables,
you got it wrong, instance variables are not overriden in sub-class. inheritence and polymorphism doesnt apply for instance fields. they are only visible in your sub-class if they are marked protected or public. currently you have super class variable marked private. no other class can access it. mark it either protected or public in-order for other class's to access it.
public class A{
public int num=5;
public static void main(String[] args) {
b d = new b();
d.c();
}
}
class b extends A
{
public void c()
{
System.out.println(num);
}
}
definitely this is what you need i think
private scope can only be accessed by the containing class.
For this to work num would need to be declared protected scope.
However this would also make it accessible to other classes in the same package. My recommedation would be to create a get / set method in order to maintain proper encapsulation.
you could then access num in class b by calling getNum()
Because you are using the private access modifier. If you use private to a instance variable or to a method it only can access inside the class only(even several classes include one source file). We can expose private variable to outside by using getters and setters. Following code will compile without an error
public class A {
private int num;
public void setNum(int num)
{
this.num = num;
}
public int getNum()
{
return num;
}
public static void main(String[] args)
{
B d = new B();
}
}
class B extends A
{
public B()
{
SetNum(5);
System.out.println(getNum());
}
}
You don't have access to private members of the base classes from the subclass. Only the members with modifiers of private/protected
I am trying to understand my way around polymorphism in Java. I created a parent class that has too many common methods that all children will use in the same manner.
Each of the subclasses' children all share static information, These variables or information will be used in the methods declared only in the parent.
The problem wish accessing static variables from Parent methods seems not really possible,
Its a solution to declare the common information per instance but since there will be 1000s of instances its such a waste of memory.
A simple elaboration of what i mean is the following code :
class testParent {
static int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
static
{
testChild2.k =2;
}
}
public class testChild1 extends testParent{
static
{
testChild1.k = 1;
}
public static void main(String[] args)
{
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
the output i expect was
1
2
1.
but what happens is :
1
2
2
One might think that on the initiation of each subclass the static variables of this subclass is set and then all methods referring to this subclass has access to the corresponding 'k' value.
But what actually happens is that all subclasses edit in the same static variable that is shared along all subclasses and hence destroys my whole point of using static variables for each subclass and its instances and using commmon methods in the Parent accessing these variables.
Any idea how can this be done ?
An option is to access the subclasses' static data through an abstract (non-static) method:
abstract public class Parent {
protected abstract int getK();
public void print() {
System.out.println(getK());
}
}
public class Child1 extends Parent {
private static final int CHILD1_K = 1;
protected int getK() { return CHILD1_K; }
}
public class Child2 extends Parent {
private static final int CHILD2_K = 2;
protected int getK() { return CHILD2_K; }
}
When you make new testChild2().print(); the static block on testChield2 was executed and change the value to 2.
static blocks only execute once when loaded by the ClassLoader.
This one give the output you want:
class testParent {
static int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
{
testChild2.k =2;
}
}
public class testChild1 extends testParent{
{
testChild1.k = 1;
}
public static void main(String[] args)
{
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
Non static code blocks execute everytime the class is instanciated.
Premature optimization is the root of all evil. I don't think you'll run into any memory issues with thousands of instances, each with their own data, unless you're working on a tiny embedded system of some kind. Static variables are not intended to do what you're trying to do with them.
Static variables are specific to the class itself. If you want the same field in different instances of a class to have different values, then that field cannot be static.
The solution: don't make k static.
class testParent {
int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
{
this.k =2;
}
}
class testChild1 extends testParent{
{
this.k = 1;
}
public static void main(String[] args){
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
Demo
(ignore the static class business - that's just to make it work in ideone).