mikebai.com

  • Home
  • dev
  • DotNET
  • M365
  • 搞笑
  • 杂七杂八
  • FocusDict
個人BLOG
it developer
  1. Main page
  2. dev
  3. Main content

java的super和C#中的base

2011-03-01 127hotness 0likes 0comments

using System;
using System.Collections.Generic;
using System.Text;


namespace ConsoleApplication4
{
    public class Person
    {
        public string name;
        public uint age;
        public Person(string name, uint age)
        {
            this.name = name;
            this.age = age;
            Console.WriteLine(name);
            Console.WriteLine(age);
        }
    }
    public class Student : Person
    {
        private uint id;
        public Student(string name, uint age, uint id)
            : base(name, age)
        {
            this.id = id;
            Console.WriteLine(id);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student("lihaifeng", 15, 2);
        }
    }
}
//这个是C#中的base,base关键字用于从派生类中访问基类成员。即使基类的方法已经在派生类中重写,仍然可以使用base关键字调用。在创建派生类的实例时,可以使用base关键字调用基类的构造方法。base关键字只能访问基类的构造方法,实例方法,和实例属性,不能访问基类的静态方法


package mypackage;
class Base{
Base(){


}
Sub s = new Sub();


public void m(){
System.out.println("父类的方法");
}
}
class Sub extends Base{


Sub(){
super(); //调用父类的构造方法
super.m();//调用父类的方法
}
public void n(){
System.out.println("子类的方法");


}
public static void main(String[] args){
Sub s = new Sub();
s.m();//这里应该理解为:
//子类继承了父类,那么这个m()应该属于子类的了!,所以我们在重写的时候要覆盖父类的方法! 那么这里算调用子类自己的方法了
Base b = new Base();
b.m();//父类对象调用自己方法


b.s.n(); //父类调用子类的方法
//b.n();//编译错误,因为子类的方法对父类不可见!
}
}


abstract class Shape{
protected double length;
protected double width;
Shape(double num,double num1)
{
   this.length=num;
   this.width=num1;
  
}
abstract double area();
}
class Square extends Shape{
Square(double a,double b){
super(a,b);}
double area()
{
   System.out.println("正方形的面积为:"+length*width);
   return length*width;
  
}

}
class Triangle extends Shape{
Triangle(double a,double b)
{
   super (a,b);
}
double area()
{
   System.out.println("三角形的面积为");
   return (0.5*length*width);
}
}


class CalculateArea{
protected CalculateArea()
{}
public static void main(String args[])
{
   Shape fobj;
   Square sqobj=new Square(10,20);
   Triangle trobj=new Triangle(12,8);
   fobj=sqobj;
   System.out.println(fobj.area());
   fobj=trobj;
   System.out.println(fobj.area());
  
}
}


示例声明了一个Shape的抽象类。这个类包含一个名为area()的抽象方法,两个类square和traingle派生自shape类并重写方法area().          


shape类的对象不能被实例化,因为他是抽象的,对象fobj声明为sha

Tag: Nothing
Last updated:2011-03-01

mikebai

This person is a lazy dog and has left nothing

Like
< Last article
Next article >

COPYRIGHT © 2025 mikebai.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang