Is it possible to call base class function without modifying both base and derived classes?
class Employee {
public String getName() {
return "Employee";
}
public int getSalary() {
return 5000;
}
}
class Manager extends Employee {
public int getBonus() {
return 1000;
}
public int getSalary() {
return 6000;
}
}
class Test {
public static void main(String[] args) {
Employee em = new Manager();
System.out.println(em.getName());
// System.out.println(em.getBonus());
System.out.println(((Manager) em).getBonus());
System.out.println(em.getSalary());
}
}
Output:
Employee
1000
6000
How shall I call the Employee's getSalary() method on em object?
You can't. You could add a method like this to Manager if you wanted:
public int getEmployeeSalary()
{
return super.getSalary();
}
Use an Employee object instead:
Employee em = new Employee();
You can call the superclass's method from within the subclass.
class Manager extends Employee {
public int getBonus() {
return 1000;
}
public int getSalary() {
return super.getSalary();
}
}
Related
I started to programm in Java since Yesterday, and I have the biggest question of my entire programmer life(since Yesterday).
For example, let's say I have a code like this:
public class itsAClass {
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
return A;
}
}
I wanted to use the method something() in another Class to get the String Sentence of A, but I got only null.
How can I change the value of A, so that the another Class can get the Value "This should be changed"?
If you just want to bring this code to work you just can make something() static as well.
But this will be not the right way to approach this problem.
If you want to hold code in the main class you could do something like this:
public class AClass {
private String a;
public static void main() {
AClass myC = new AClass();
myC.setA("This should be changed");
// than use myC for your further access
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
If you want to access it by a external class without direct reference you can checkout the singleton pattern.
public class AClass {
private final static AClass INSTANCE = new AClass();
private String a;
public static void main() {
getSingleton().setA("This should be changed");
}
public String something() {
return a;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public static AClass getSingleton() {
return INSTANCE;
}
}
This way you can access it via AClass.getSingleton() from any location of your code.
You have to call your main() function.
In another class:
itsAClass aClassObj = new itsAClass();
aClassObj.main();
// or rather itsAClass.main() as it is a static function
// now A's value changed
System.out.println(aClassObj.something());
the way to set the value of private variable is by setter and getter methods in class.
example below
public class Test {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}
you can call method main() in method something().
public class itsAClass{
static private String A;
public static void main() {
A = "This should be changed";
}
public String something() {
main();
return A;
}
public static void main(String[] args){
itsAClass a1 = new itsAClass();
System.out.println(a1.something());// prints This should be changed
}
}
I am writing a code that create an array of instances of Account object in another class (Bank).
I am initializing the array inside the main method, but it is not accessible inside the Bank class.
What I want to do is create 4 instances of the Account class and to be able to perform all tasks inside the Bank class methods. Is there a way that I can do this?
this is my code
Account.java
package question1;
import java.util.Date;
public class Account {
public int AccountNum;
public double BALANCE;
public Date OPENDATE;
public String OwnerName;
public Account() {
// TODO Auto-generated constructor stub
}
public Account(int accnum, double balance, Date opendate, String ownername) {
this.AccountNum = accnum;
this.BALANCE = balance;
this.OPENDATE = opendate;
this.OwnerName = ownername;
}
public int getAccountNum() {
return AccountNum;
}
public void setAccountNum(int accountNum) {
AccountNum = accountNum;
}
public double getBALANCE() {
return BALANCE;
}
public void setBALANCE(double bALANCE) {
BALANCE = bALANCE;
}
public Date getOPENDATE() {
return OPENDATE;
}
public void setOPENDATE(Date oPENDATE) {
OPENDATE = oPENDATE;
}
public String getOwnerName() {
return OwnerName;
}
public void setOwnerName(String ownerName) {
OwnerName = ownerName;
}
public double yearlyInterest(double balace) {
return balace;
}
}
Bank.java
package question1;
public class Bank {
public static void main(String[] args) {
Account[] acc = new Account[4];
for(int i = 0 ; i<acc.length; i++){
acc[i] = new Account();
System.out.println(acc[i].toString());
}
/// how to continue form here ??
}
}
Call the constructor of the Account class. Now you can set all arguments as desired. Afterwards, you can add the instance to any array or collection.
List<Account> accounts = new ArrayList<Account>(4);
Account myAccount = new Account(123, 100.5, new Date(), "dev leb");
accounts.add(myAccount);
You probably want to have a property of an Account array in your class.
You can set your property in the class body:
public class Bank {
//Set your property here.
private Account[] _acc;
//Initialize in ctor.
public Bank() {
_acc = new Account[4];
}
//....
//You can then use it as a property in your code.
//If needed outside the class, set up setter and getter methods,
//avoiding violating encapsulation.
public Account[] getAcc(){
return _acc;
}
public void setAcc(Account acc){
this._acc = acc;
}
//If you need this to be used inside main, then you must instantiate a
//Bank in main and then make all the appropriate operations there.
public static void main(String[] args) {
Bank bank = new Bank();
Account[] bankAccounts = bank.getAcc();
//....
}
}
My suggestion though is that you use an ArrayList instead:
Set the property:
private List<Account> acc;
And in constructor:
acc = new List();
In order to add an account in a class method:
acc.add(new Account());
In order to retrieve an element by indexing:
acc.get(0);
for more information, look at the ArrayList JavaDoc.
If you are not able to understand why your array that is defined inside the main is not accessible inside your Bank class, then I suggest you search more about Object-Oriented programming, Class definition, instantiation and properties accessibility and manipulation and static methods in Java.
MyMath's constructor is supposed to call Homework's constructor, but super(); returns an error 'cannot find symbol'. It should not have any arguments.
Also, I am confused about how to call the method createAssignment using an arraylist, but I have to use it. Any advice?
Homework
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
public Homework(int pages, String hw) {
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath() {
super();
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
public class testHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
list.add(new MyMath(1));
list.add(new MyJava(1));
for (Homework s : list) {
s.createAssignment();
}
}
}
Compiler error:
Regarding the compiler error, you have to change the MyMath constractor to somthing like:
public MyMath() {
super(someInt, someString);
}
Or, you can add a non-arg constructor to the Homework class:
public Homework() {
this(someInt,someString);
}
You can learn about the super() keyword in the Javadocs tutoriel:
If a constructor does not explicitly invoke a superclass constructor,
the Java compiler automatically inserts a call to the no-argument
constructor of the superclass. If the super class does not have a
no-argument constructor, you will get a compile-time error. Object
does have such a constructor, so if Object is the only superclass,
there is no problem.
Code Suggestion:
As there is many other issues in your question, i modified all your classes like below:
Homework.java:
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
{
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public Homework(int pages, String hw) {
this.pagesToRead = pages;
this.typeHomework = hw;
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath.java
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath(int pages, String hw) {
super(pages,hw);
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
TestHomework.java:
class TestHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
// will create a homework with type Math and one page to read
list.add(new MyMath(1,"Math"));
// Assuming MyJava is similar to MyMath
list.add(new MyJava(1,"Java"));
for (Homework s : list) {
if (s instanceof MyMath) {
// modify the number of pages to read for the Math homework
s.createAssignment(3);
} else if (s instanceof MyJava) {
// modify the number of pages to read for the Java homework
s.createAssignment(5);
} else {
s.createAssignment(7);
}
}
}
}
The abstract method statement (in the super class) must be implemented to return a string representation of a statement.
So I've done the following:
public abstract String statement(); //The abstract method in my super class
..and the method in my subclass:
//#Override
public String statement()
{
return String.format("Account no %d has balance R%d and minimum balance R%d", accountNumber,balance,getMinBalance());
}
My main class just calls the Account class (the super class in question) as follows:
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]); //ao being the array which contains the values.
However, the console just terminates without displaying anything (I'm also not familiar with implementation).
Here's the full code:
Main:
public class AccountList
{
public static void main(String[] args)
{
int[] ao = {00000,0,0,12345,500,250,23456,230,-50,34567,340,500,45678,-320,-50,56789,-320,-500};
for(int i=0;i<ao.length;i=i+3)
{
int a = i+2;
if(ao[a]>=0)
{
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
}
if(ao[a]<=0)
{
new ChequeAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
}
}
}
}
Super class:
public abstract class Account implements InterestAccount
{
static String accountNumber;
int balance;
public Account()
{
accountNumber = "00000";
balance = 0;
//statement();
}
public Account(String accountNumber,int balance)
{
setAccountNum(accountNumber);
setBalance(balance);
}
public void setAccountNum(String accNum)
{
accountNumber = accNum;
}
public void setBalance(int balance)
{
this.balance = balance;
}
public String getAccountNumber()
{
return accountNumber;
}
public int getBalance()
{
return balance;
}
public abstract String statement();
}
One of the sub-classes:
public class SavingsAccount extends Account
{
int minBalance;
public SavingsAccount()
{
super();
minBalance = 0;
}
public SavingsAccount(String accountNum,int minBalance,int balance)
{
super(accountNum,balance);
setMinBalance(minBalance);
}
public void setMinBalance(int minBalance)
{
this.minBalance = minBalance;
}
public int getMinBalance()
{
return minBalance;
}
#Override
public int calculateInterest(int value) {
if(minBalance>balance)
{
return 0;
}
else
{
return (minBalance*balance)/100;
}
}
//#Override
public String statement()
{
return String.format("Account no %d has balance R%d and minimum balance R%d", accountNumber,balance,getMinBalance());
}
}
You never calls the method statement.
1) create a new SavingsAccount object
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
2) Constructor class got call by above statement
public SavingsAccount(String accountNum,int minBalance,int balance)
{
super(accountNum,balance);
setMinBalance(minBalance);
}
3) Subclass then call superclass method
public Account(String accountNumber,int balance)
{
setAccountNum(accountNumber);
setBalance(balance);
}
4) SetBalance is called
public void setBalance(int balance)
{
this.balance = balance;
}
5) setMinBalance called
public void setMinBalance(int minBalance)
{
this.minBalance = minBalance;
}
6) End of create object SavingsAccount
No single statement calling the method statement
It might help to know more of your code, but from what I see, there are some possible cases:
Your code runs and terminates without an error. Reason you don't see anything is, there is nothing written to the standard output stream (e.g. via System.out.println()).
Your code has some internal problems, which cause an exception, which again is not shown due to a broken logging mechanism.
In any case, use a debugger to step through you code and determine which parts run perfectly and if any fail. It might help to extract some local variables, give them proper meaningful names and watch their contents during execution.
Im learning java and I have problem with get and set methods in other classes.
My first class is named Department and second is named Company. I would like to set number of staff in class Department and get number of staff in class Company.
Department class
public class Department {
public int staffNumber;
public Department() {
}
public void setStaffNumber(int staff) {
this.staffNumber= staff;
}
}
Company class
public class Company {
public Department staffNumber;
public Company() {
}
public Department getStaffNumber() {
return Department.staffNumber = Department.staffNumber;
}
}
Can you please help me with error message - non-static variable staffNumber cannot be referenced from a static context ?
Thank you
The problem is here:
return Department.staffNumber = Department.staffNumber;
The compiler will read Department.staffNumber as: staffNumber is a static variable in the Department class. There your problem.
In order to solve this, you should just return the instance data:
public Department getStaffNumber() {
//<Department attribute in the class>
return staffNumber;
}
By the way,even if you have a Department.staffNumber static attribute inside the Department class, the proposed line return Department.staffNumber = Department.staffNumber; won't make any sense. It's similar to this:
public class SomeClass {
int x;
public int getX() {
//return x = x; //clumsy
return x; //now this might be better
}
}
You are trying to acces the variable staffNumber as it was a static variable.
If you want to return the staffNumber, you should return staffNumber.staffNumber. You are using bad semantics though...you should have:
public class Company {
public Department m_department;
public Company() {
m_department=new Department();
}
public Department getStaffNumber() {
return m_department.staffNumber;
}
}
public Department getStaffNumber() {
return Department.staffNumber = Department.staffNumber;
}
Department.staffNumber is accessed like a static variable.
It should be return staffNumber.
Your getter normally wouldn't init. It should just return.
If you want to return Department then it should be return staffNumber
If you want to return Department.staffNumber it should be
return staffNumber.staffNumber changing the return type to an int... and fix the variable names!
You seem to be confused about basic concepts.
Do the following
public class Department {
public int staffNumber;
public Department() {
}
public void setStaffNumber(int staff) {
this.staffNumber= staff;
}
public int getStaffNumber() {
return staffNumber;
}
}
Now using StaffNumber in your Company class
public class Company {
public Department dept;
public Company() {
dept= new Department();
}
public int getDepartmentStaffNumber() {
return dept.getStaffNumber();
}
public void setDepartmentStaffNumber(int staff) {
dept.setStaffNumber(staff)
}
}