I am new to Java Programming and i am trying to experiment with inheritance and constructors.
My parent class:
class user{
private String name;
private float balance;
private int accno;
private int passw;
public String getName()
{
return name;
}
.
.
.
//getters and setters for the remaining variables.
}
My derived class:
class userFunct extends user
{
userFunct(int accno,String name,int passw,float bal){ //parametrized constructor
super.setPassw(passw);
super.setName(name);
super.setAccno(accno);
super.setBalance(bal);
}
In my main program, i do this:
public static void main()
{
userFunct obj=new userFunct(accno,name,passw,bal); //Creating an object userFunct
.
.
.
}
I get an error saying
variable accno may not have been initialized
Now since this had lots of lines i wrote a smaller piece of code
import java.util.*;
import java.io.*;
class a{
public int x;
}
class b extends a{
/*static*/ void pri(a obj)
{
System.out.println("Class b"+obj.x);
}
b(int num)
{
super.x=num;
}
}
public class Main
{
int num=9;
public static void main(String[] args) {
b objb=new b(9);
objb.pri(objb);
}
}
And this works fine, with proper outputs. I cannot spot the mistake when i compare the two codes.
I don't know if this is some silly mistake on my side or if there is some underlying concept that i have failed to understand. Either ways, I would like to know what is happening here
The difference between two code you shared in user class you declared all variable as private and not initialised. In your class a you declared variable as public.
So assign a initial value to all variable an enjoy
class user {
String name = "";
float balance = 0.0f;
int accno = 0;
int passw = 0;
public String getName()
{
return name;
}
public void setName(String name) {
this.name = name;
}
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
public int getAccno() {
return accno;
}
public void setAccno(int accno) {
this.accno = accno;
}
public int getPassw() {
return passw;
}
public void setPassw(int passw) {
this.passw = passw;
}
}