How can I use variables from one class in my other classes? For example, I have
Class 1
public class maintype {
public int A = 1,
B = 2,
C = 3,
D = 4;
public String E, F, G
public static void main(String args[]) {
}
}
Class 2
public class subclass {
public numbers() {
AB = A + B;
}
}
I want to use the variable a and b in my second class but it is giving me an error. saying no such variable exist but I don't want to create that variable again in my second class.
you forgot to extend
public class subclass extends maintype{
public numbers(){
AB = A+B;
}
}
You can extend the class as in::
public class subclass extends maintype{
public numbers(){
AB = A+B;
}
}
This is the common feature of java Called Inheritance, Explained below::
Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).
Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.
For more details follow this link::
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
You forgot the extends keyword in subclass, so I have corrected it for you.
Superclass:
public class superclass{
public static int A = 1;
public static int B = 2;
public static int C = 3;
public static int D = 4;
public String str1 = "E";
public String str2 = "F";
public String str3 = "G";
public static void main(String[] args){
//What do you want to put here?
}
}
Subclass:
public class subclass extends superclass {
public void numbers(){
int A = superclass.A;
int B = superclass.B;
int AB = A + B;
}
}
Related
Can someone explain why the output is 10 and not 20?
Why does the object refers to the value of the parent class instead of the class it is assigned to?
class A {
int i = 10;
}
class B extends A {
int i = 20;
}
public class MainClass {
public static void main(String[] args) {
A a = new B();
System.out.println(a.i);
}
}
The instance you're creating is of type A, so since both variables have the same name, you'll get the superclass' one, if you want B's you should do
B b = new B()
System.out.println(b.i)
You shouldn't use variables of the same name like that in between superclasses and subclasses, gets very confusing and kinda defeats the purpose of inheriting.
In Java, methods are overridden not variables. So variables belong to their owner classes. a is a reference of type A that point to an object of type B but remains of type A.
To call the i of B, you have to cast a to B.
A a = new B();
System.out.println(((B)a).i);
Can someone explain why the output is 10 and not 20?
Since the value of i is defined in the class A and is NOT overridden/re-assigned by the definition of class B as you might just be assuming. Adding a custom constructor could clarify your doubts further of what you might be intending to do:
class A {
int i = 10;
}
class B extends A {
public B() {
this.i = 20;
}
}
A a = new B();
System.out.println(a.i); // would now print 20
Declaring the same variable i in class B would have its own scope and does not inherit from the class A.
Variables can not be overridden in Java as they are resolved at compile-time; You can use super to set its values,
class A {
int i = 10;
}
class B extends A {
int i = 20;
public B() {
super();
super.i = i;
}
}
A a = new B();
System.out.println(a.i); //20
i want no one to override my constructor trying to use private method but it is giving my error how to stop overriding my constructor
class bc {
int a;
bc() {
System.out.println("hi this is construvtor ");
a = 10;
System.out.println("the value of a=" + a);
}
}
class dc extends bc {
int b;
dc() {
a = 20;
System.out.println("derived dc");
System.out.println("derived value of a=" + a);
}
}
public class sup {
public static void main(String[] args)
{
dc s1 = new dc();
}
}
Constructors are not overriden, methods are.
As you add a constructor in a subclass with the same parameters as which one of the parent class, it doesn't override which one of the parent.
It provides only a way to instantiate the subclass in the same way that the parent class constructor is invoked.
Using private constructor in the parent class will just make the class not inheritable as a child class constructor needs to invoke the parent constructor and the private constructor in the parent class prevents it.
Constructors can't be overridden because they are not member of class. Sub class constructor invokes super class default constructor by default. If you don't want it to be invoked, then you can make a parameterized constructor in super class and call it in subclass constructor.
class bc {
int a;
bc() {
System.out.println("hi this is construvtor ");
a = 10;
System.out.println("the value of a=" + a);
}
bc(int i){}
}
class dc extends bc {
int b;
dc() {
super(1); // invoking super class parameterized constructor
a = 20;
System.out.println("derived dc");
System.out.println("derived value of a=" + a);
}
}
public class sup {
public static void main(String[] args)
{
dc s1 = new dc();
}
}
It's correct that constructors are not overridden. But I wold like to add up some info according to your query.
You can make a constructor of the parent class private only if you have another constructor on the parent class with non-private specifier and in that case you have to call that non private super class constructor from the child class constructor using super.
N.B.: Although there is no practical use case in doing such thing. Just for the sake of your query of private constructor. Try below code:
class bc {
int a;
private bc() {
System.out.println("-----------------------");
}
private bc(int s){
System.out.println("write logic");
}
bc(int a,int b){
System.out.println("***************");
}
}
class dc extends bc {
int b;
dc(int a) {
super(8,9);
}
}
public class sup {
public static void main(String[] args)
{
new dc(9);
}
}
I have three classes as following, class b and c are extending class a. I am wondering why the code is not reading the value of b and c variables.
public class a{
protected int myvalue = 1;
}
public class b extends a{
private int myvalue = 2;
}
public class c extends a{
private int myvalue = 3;
}
body of my main method
ArrayList<a> myList= new ArrayList();
myList.add(new b());
myList.add(new c());
for(int i =0;i<myList.size();i++)
System.err.println("value is:" + myList.get(i).myvalue);
output
1
1
From Oracle website:
Within a class, a field that has the same name as a field in the
superclass hides the superclass's field, even if their types are
different. Within the subclass, the field in the superclass cannot be
referenced by its simple name. Instead, the field must be accessed
through super, which is covered in the next section. Generally
speaking, we don't recommend hiding fields as it makes code difficult
to read.
You are shadowing your field myvalue and not overriding it, I believe something like this will do what you want
public class a{
protected int myvalue = 1;
}
public class b extends a{
public b() {
myvalue = 2;
}
}
public class c extends a{
public c() {
myvalue = 3;
}
}
Also, please don't use Raw Types
// ArrayList<a> mylist = new ArrayList();
ArrayList<a> mylist = new ArrayList<>(); // <a> on Java 5 and 6
Can somebody please tell me if the keyword 'extends' must be an used (in the syntax) of child classes that overide methods of their super class.
The word extends is used to indicate for the whole class that this class is a sub-class of another class. It is not related to whether the sub-class overrides certain methods or not, that is entirely up to the sub-class class. The sub-class may decide to override none, some, or all of the methods of the super-class. The sub-class may override only methods which are not marked as final in the super-class.
Here is a somewhat trivial example:
class A {
// This is the super-class.
public void myMethod() {...};
}
class B extends A {
// This extends above says: B is sub-class of A.
// So this class B is the sub-class of A.
// You can override methods of A here, like this
public void myMethod() {...};
// but you're not required to override them.
}
Polymorphism in java is a concept by which we can perform a single action by different ways.it uses 2 concepts such as method overloading and method over riding.
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilising the method's name.
the method over riding concepts uses the key word 'extends'.
We can extend a class by using the extends keyword in a class declaration after the class name and before the parent class.
public class ParentClass {
}
and we define child class like
public class ChildClass extends ParentClass {
}
// example of extending a class
class B {
int x = 0;
void f1 () { x = x+1;}
}
class C extends B {}
public class Test1 {
public static void main(String[] args) {
B b = new B();
b.f1();
System.out.println( b.x ); // prints 1
}
}
// example of extending a class, overwriting a method
class B {
int x;
void setIt (int n) { x=n;}
void increase () { x=x+1;}
}
class C extends B {
void increase () { x=x+2;}
}
public class Test2 {
public static void main(String[] args) {
B b = new B();
b.setIt(2);
b.increase();
System.out.println( b.x ); // prints 3
C c = new C();
c.setIt(2);
c.increase();
System.out.println( c.x ); // prints 4
}
}
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;
}