JAVA: Square and Cube Class
Tarih: 24 Mart 2014 Yorum: 0

Write 2 classes which are public and named Square and Cube.

The class Cube extends the class Square.

The class Square has 2 fields which are protected integers named x and y. It has one constructor that takes two integers and assigns them to x and y. Finally it has 1 protected method named computeArea the returns an integers after calculating the area of the square. The method fets no arguments.

The class Cube has one field which is a private integer named z. It has one constructor takes three integer arguments and calls its super-class constructor to assign x and y values, and then it assigns z value in its own constructor. Finally, it overrides the method computeArea. This method calls super-class method computeArea and multiplies the result with 6 to compute the area of the cube and returns this integer value.

Test Class: Create two objects which are Square and Cube and compute and print their areas.

 

Square.java

public class Square {
    protected int x,y;

    public Square(int x, int y){
    	this.x	= x;
    	this.y	= y;
    }

    protected int computeArea(){
    	return this.x * this.y;
    }   
}

 

Cube.java

public class Cube extends Square {
	private int z;

    public Cube(int z,int x, int y) {
    	super(x,y);
    	this.z 	= z;	
    }

    protected int computeArea(){
    	return super.computeArea() * this.z; 
    }
}

 

Test.java

public class Test {

    public static void main(String [] args){   	

    	Square sq = new Square(4,4);
    	Cube cb	= new Cube(4,4,6);

    	System.out.println("Square's area: " + sq.computeArea());
    	System.out.println("Cube's area: " + cb.computeArea());
    }
}



Yorum Yok:


Yorum Yap:

Yorum yapabilmek için giriş yapmalısınız.




tema yapımcısı wordpress alexa bilgileri Webmaster Creative Commons v3 ile Lisanslanmıştır!


Akif ARSLAN © 2012 - 2024
Sitede bulunan istediğiniz cümleyi veya içeriği, istediğiniz gibi, istediğiniz yerde, istediğiniz zaman ve istediğiniz kişilerle paylaşabilirsiniz.