i am trying to execute percentage of marks using abstract class in salesforce and i got below error

317 Views Asked by At
public class StudentA extends marks \\child class
{
    public double maths;
    public double chemistry;
    public double physics;
    double percentage;

    public StudentA(integer maths, integer chemistry, integer physics)
    {
        system.debug('maths marks are' + maths);
        system.debug('chemistry marks are' + chemistry);
        system.debug('physics marks are' + physics);
    }
    
    public double percentage()
    {

        percentage = (maths+chemistry+physics/3);
        
        system.debug('percentage is' + percentage);
        
        return percentage;
    }
      
    public override void getpercentage()
    { 
        system.debug('total percent' + percentage);
           
    }
   
    
}


object: 

StudentA v = new StudentA(99,98,99);
v.percentage();
v.getpercentage();

Note: I am trying to calculate total percentage of marks obtained, when i executed it give me error "attempt to de-reference null object".

In output only marks are printed. enter image description here error screen shot is attached and output is also executed.

enter image description heremgur.com/tiJe2.png

2

There are 2 best solutions below

2
On

You are not assigning the parameter values to the class variables

Please modify your code as follows:

public class StudentA extends marks \\child class
    {
    public double maths;
    public double chemistry;
    public double physics;
    double percentage; // can remove this line

    public StudentA(integer maths, integer chemistry, integer physics)
    {
        this.maths = maths;
        this.chemistry = chemistry;
        this.physics = maths;
    }
    
    public double percentage()
    {

        percentage = (maths+chemistry+physics/3);
        
        system.debug('percentage is' + percentage);
        
        return percentage;
    }
      
    public override void getpercentage()
    { 
        system.debug('total percent' + percentage);
           
    }
  }

     StudentA v = new StudentA(99,98,99);
     v.percentage();
     v.getpercentage();
2
On

You are passing in your variables but not setting them.

In your constructor do

Maths = maths;
Chemistry = Chemistry;
Physics = Physics;